Any need to call unsubscribe for RxJS first()
Asked Answered
H

3

32

In the following code:-

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

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

Harwilll answered 6/4, 2018 at 0:43 Comment(0)
E
49

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.

Enterprising answered 17/11, 2018 at 2:38 Comment(5)
Think you are missing a ) :)Nedrud
what happens when the source observable never emits a value, does that mean that the Subscription stays there and possibly create a memory leak ?Cripps
@Cripps Yes, it can create a memory leak.Hemp
So how to add unsubscribing in this case?Monseigneur
takeUntil(this.destroyed$) Where destroyed$ gets set on ngOnDestroy()Gratulant
P
6

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.

Pachalic answered 6/4, 2018 at 2:23 Comment(1)
Changed to 1,2 but your answer still is correct since you mentioned it Completes.Harwilll
K
3

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
)
Kroo answered 6/4, 2018 at 1:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.