user1145347
user1145347

Reputation: 341

Immediately unsubscribing from RxJS Observable

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**
});

Upvotes: 28

Views: 10074

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657068

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

will end the subscription after the first event.

Update for RxJs 6+

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

Upvotes: 59

Related Questions