26

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**
});
erikvimz
  • 5,256
  • 6
  • 44
  • 60
user1145347
  • 321
  • 3
  • 8
  • Possible duplicate of [How to unsubscribe from EventEmitter in Angular 2?](http://stackoverflow.com/questions/36494509/how-to-unsubscribe-from-eventemitter-in-angular-2) – jmachnik Oct 13 '16 at 11:05
  • 1
    take(1) seems to be a better option compared to first() https://stackoverflow.com/questions/42345969/angular-2-using-rxjs-take1-vs-first – Ngoc Nam Nguyen Jan 25 '18 at 00:56

1 Answers1

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

will end the subscription after the first event.

Update for RxJs 6+

observable.pipe(first()).subscribe(....)
Vamshi
  • 9,194
  • 4
  • 38
  • 54
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    This is the approach I was looking for. Thanks – user1145347 Oct 13 '16 at 11:15
  • 6
    There are other similar operators like `.take(1)` or `.skip(5).take(1)` to get the 6th event only. – Günter Zöchbauer Oct 13 '16 at 11:16
  • So if I use `take` or `first` I won't be getting any emission in the future, is it right? Does it apply to [`BehaviorSubject`](http://reactivex.io/rxjs/class/es6/BehaviorSubject.js~BehaviorSubject.html) as well? – Wesley Gonçalves Jul 12 '20 at 00:38
  • Not sure what you expext. If you say you want the first or take 5 then that is what you get. Why would you expect something else? – Günter Zöchbauer Jul 12 '20 at 03:51
  • 1
    @GünterZöchbauer, I am learning Observables and trying to understand its logic. It makes sense what you've said. But I thought that I could take 5, do something with them and maybe in the future get new updates/new values. – Wesley Gonçalves Jul 13 '20 at 13:06
  • 1
    I see. No, this is not how it works. You'd need to count yourself in `subscribe` or whatever method you use process events and count yourself and skip using `if(...)` if it is a position you do not care of. – Günter Zöchbauer Jul 13 '20 at 14:46
  • Got it. Thanks @GünterZöchbauer – Wesley Gonçalves Jul 13 '20 at 20:02