Reputation: 607
in RxJS I'd like to take some special action once an Observer subscribes to an Observable and when he unsubscribes. I can of course overwrite the subscribe()
and unsubscribe()
methods, but that seems crud.
Isn't there a way during creation of the observable to supply callbacks that get called whenever someone subscribes/unsubscribes?
BR,
Daniel
Upvotes: 4
Views: 3677
Reputation: 29896
This is what Observable.create
is for. You can create your own observable with specified attach/detach handlers, and can even wrap existing observables with just 2 additional lines of code.
const obs = Rx.Observable.create(observer => {
console.log('attach');
// If you want to wrap another observable, call this:
// const subs = other.subscribe(observer);
return () => {
// subs.unsubscribe();
console.log('detach');
};
});
console.log('subscribe subscription1');
const subscribtion1 = obs.subscribe(() => {});
console.log('subscribe subscription2');
const subscribtion2 = obs.subscribe(() => {});
setTimeout(() => {
console.log('subscribtion1.dispose()');
subscribtion1.unsubscribe();
}, 500);
setTimeout(() => {
console.log('subscribtion2.dispose()');
subscribtion2.unsubscribe();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.0-rc.4/Rx.js"></script>
Upvotes: 5