4

I want to unsubscribe the observable, shall i use the first() operator for unsubscribe?

Example below,

Rx.Observable.interval(100)
.do(x => console.log(x))
.first()
.subscribe(x => x);

Is the above code will do automatic unsubscribe or need to do anything?

Jeyabalan Thavamani
  • 3,057
  • 8
  • 21
  • 33
  • Possible duplicate of [Angular 2 using RxJS - take(1) vs first()](https://stackoverflow.com/questions/42345969/angular-2-using-rxjs-take1-vs-first) – Meeker Feb 27 '18 at 23:56

2 Answers2

3

The first() operator takes an optional predicate function and emits an error notification when no value matched when the source completed.

It will unsubscribe after whatever emits first. So to answer your question you do not need to do anything. It will unsubscribe.

Angular 2 using RxJS - take(1) vs first()

Meeker
  • 5,979
  • 2
  • 20
  • 38
0

The example that you have given is unsubscribed automatically after the first value is submitted. Use bellow example

Rx.Observable.interval(100)
.first()
.subscribe(
  x => { 
   console.log(x)
 }, err => {
   console.log("error")
 }, () => {
   console.log("Completed");
});

Normally first() operator is used to get the first value of a sequence. I'm not sure whether we can use it for everywhere when we want to unsubscribe.

Ajantha Bandara
  • 1,473
  • 15
  • 36