I am seeking a way to automatically subscribe to an observable (triggerEvent
) when another observable (observedEvents
) has been subscribed to. My goal is to activate triggerEvent
without manual intervention, only once there is a subscription to observedEvents
.
Below is a code snippet illustrating my requirements:
// This section emits events
let emitting = new EventEmitter();
// Main Observable that may be accessed by others
let observedEvents = Rx.Observable.merge(
Rx.Observable.fromEvent(emitting, 'aba'),
Rx.Observable.fromEvent(emitting, 'bob')
)
// I want this trigger to get a subscription as soon as
// observedEvents has one, meaning when I subscribe to
// observedEvents, it activates this trigger
// I tried using skipUntil, but instead of skipping one event,
// I'm looking for continuous activation
let triggerEvent = Rx.Observable.merge(
Rx.Observable.of('a').delay(200),
Rx.Observable.of('b').delay(400),
Rx.Observable.of('c').delay(600)
).skipUntil(observedEvents);
// Something should trigger the activation of triggerEvent
// without manual intervention
triggerEvent.subscribe(val => {
console.log(`Perform action with ${val}`);
});
//----------------------------------------------------
// Somewhere else in the code...
//----------------------------------------------------
observedEvents.subscribe(evt => {
console.log(`Received event: ${evt}`);
});
// At this point, triggerEvent should become active
// because observedEvents now has a subscription
setTimeout(() => {
emitting.emit('bob', 'world');
setTimeout(() => emitting.emit('aba', 'stackoverflow!'), 500);
}, 200);
<!DOCTYPE html>
<html>
<head>
<script src="https://npmcdn.com/@reactivex/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c76647d4e3b203e203e236c6b7a6f2039">[email protected]</a>/dist/global/Rx.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/EventEmitter/5.1.0/EventEmitter.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
</body>
</html>
Is this approach feasible?
I trust this clarifies my requirement.
Reflecting on this scenario, utilizing Subjects appears to be the potential solution. Perhaps a gentle push in the right direction or a viable solution would be greatly appreciated.