Could anyone shed some light on how I would immediately unsubscribe from an RxJS
subscription? The observable is from Angular 2 EventEmitter
. When I recieve the event, I want to cancel the subscription. The issue here is cancelling the subscription within the function block. I have a feeling that this is the wrong approach:
this.subscription = observable.subscribe(result => {
// do something
// **unsubscribe**
});
Unsubscribing Manually One method we can use, is to unsubscribe manually from active subscriptions when we no longer require them. RxJS provides us with a convenient method to do this. It lives on the Subscription object and is simply called . unsubscribe() .
complete() after it has emitted all of it's values. There's no need to unsubscribe. It completes on it's own, which means it unsubscribes all subscribers automatically. This is also the reason why you don't often notice any memory leaks.
The take(1) For Initialization In such scenarios we can use RxJS take(1) operator which is great because it automatically unsubscribes after the first execution. The operator itself is take(n: number) so we could pass any number, but for our scenario the number 1 is all what we need!
The RxJS first() operator waits until the first value is emitted from an observable and then automatically unsubscribes, so there is no need to explicitly unsubscribe from the subscription.
observable.first().subscribe(....)
will end the subscription after the first event.
Update for RxJs 6+
observable.pipe(first()).subscribe(....)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With