Is there any differences between
Observable.pipe(take(1)).subscribe(...)
vs
const subscription = Observable.subscribe(() => { // Do something, then subscription.unsubscribe() })
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!
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.
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…
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.
The take(1)
approach has a number of advantages over subscribe
:
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.
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() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With