Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any need to call unsubscribe for RxJS first()

Tags:

rxjs

rxjs5

In the following code:-

RxJS.Observable.of(1,2).first().subscribe((x) => console.log(x););

is it necessary to unsubscribe given the operator first()?

like image 797
bhantol Avatar asked Apr 06 '18 00:04

bhantol


3 Answers

No. It unsubscribes automatically after calling first(). The current syntax is observable.pipe(first()).subscribe(func); for RxJS 6.

The documentation states:

If called with no arguments, first emits the first value of the source Observable, then completes.

like image 157
Xavier Reyes Ochoa Avatar answered Oct 16 '22 16:10

Xavier Reyes Ochoa


For the example provided, you dont need to unsubscribe, and neither you need to call first, as Observable.of(1) actually completes after emitting its first (and last) value.

like image 27
c69 Avatar answered Oct 16 '22 16:10

c69


first() will complete after the first item is emitted from the observable.

Also subscribe() takes three arguments, the last one being the complete callback. Running the following code will output 1 followed by 'done'.

Rx.Observable.of(1)
  .subscribe(
  (x) => console.log(x),    // next
  (x) => console.error(x),  // error
  () => console.log('done') // done
)
like image 3
Johan.C Avatar answered Oct 16 '22 16:10

Johan.C