Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs Observable.take(1) vs Subscription.unsubscribe()

Tags:

rxjs

Is there any differences between

Observable.pipe(take(1)).subscribe(...) 

vs

const subscription = Observable.subscribe(() => {    // Do something, then    subscription.unsubscribe() }) 
like image 962
Tuong Le Avatar asked Oct 28 '16 03:10

Tuong Le


People also ask

Does Take 1 unsubscribe from the Observable?

The take operator allows us to specify how many values we want to receive from the Observable before we unsubscribe. This means that when we receive the specified number of values, take will automatically unsubscribe! Once obs$ has emitted five values, take will unsubscribe automatically!

Do I need to unsubscribe from Observable?

In Angular applications, it's always recommended to unsubscribe the observables to gain benefits like: Avoids Memory Leaks. Aborting HTTP requests to avoid unwanted calls.

How do I unsubscribe from RxJS Observable?

Subscribing to an observable yields us Subscription object which has an unsubscribe() method. This method can be used to remove the subscription when we no longer need it. Or we can get a bit more fancy with multiple subscriptions…

Does RxJS first unsubscribe?

The RxJS first() operator waits until the first value is emitted from an observable and then automatically unsubscribes, so there is no need to explicitly unsubscribe from the subscription.


2 Answers

The take(1) approach has a number of advantages over subscribe:

  1. Code readability (and elegance).
  2. The second approach requires that you hold and manage extra variables.
  3. The second approach will not invoke the complete handler. This is because .take(1) actually create a new observable which potentially yields a single item and completes.
  4. The second approach will work for the trivial case of taking a single element, but if you need to take more then 1, take(4) will stay simple while the second approach will become hard to code.

The 3rd item is the rxjs related one, the others relate to coding style.

Have a look at a sample here.

like image 77
Meir Avatar answered Sep 20 '22 22:09

Meir


In Angular2, I find myself using both paradigms.

The first makes the most sense inside of a method, where as the second is better used in a constructor, with a cleanup in the deconstructor.

doThing(){     this.store.select('thing').pipe(take(1))         .subscribe(item => {             otherMethod(item)         }); } 

vs

class SomeClass{     public val;     private sub;     constructor(){         this.sub = this.store.select('thing')             .subscribe(item => {                 this.val = item             });     }     ngDestroy() {         this.sub.unsubscribe()     } } 
like image 41
joeydale Avatar answered Sep 22 '22 22:09

joeydale