Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immediately unsubscribing from RxJS Observable

Tags:

angular

rxjs

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**
});
like image 882
user1145347 Avatar asked Oct 13 '16 11:10

user1145347


People also ask

How do I unsubscribe from RxJS Observable?

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() .

Do I need to unsubscribe from a completed Observable RxJS?

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.

Does Take 1 automatically unsubscribe?

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!

Does RxJS first unsubscribe?

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.


1 Answers

observable.first().subscribe(....)

will end the subscription after the first event.

Update for RxJs 6+

observable.pipe(first()).subscribe(....)
like image 200
Günter Zöchbauer Avatar answered Oct 18 '22 18:10

Günter Zöchbauer