What is the best way to unsubscribe in RxJS 6?
My 'old' RxJS 5 code looks this
export class MyComponent implements OnInit, OnDestroy {
private ngUnsubscribe: Subject<any> = new Subject();
this.myService.myEventEmitter
.takeUntil(this.ngUnsubscribe)
.subscribe(this.onDataPolling.bind(this));
public ngOnDestroy(): void {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
On migration to RxJS 6 i run rxjs-5-to-6-migrate
and got
this.myService.myEventEmitter.pipe(
takeUntil(this.ngUnsubscribe))
.subscribe(this.onDataPolling.bind(this));
but this is not working because EventEmitter has no pipe method.
What is the best way to unsubscribe in RxJS 6?
Edit: This did work after a clean install and is the best way to unsubscribe in RxJS 6.
There is also a better way to unsubscribe from or complete Observables by using the takeUntil() operator. The takeUntil() operator emits the values emitted by the source Observable until a notifier Observable emits a value.
takeUntil passes values from the source observable to the observer (mirroring) until a provided observable known as the notifier emits its first value. The operator subscribes to the source observable and begins mirroring the source Observable. It also subscribes to the notifier observable.
Unsubscribing Manually RxJS provides us with a convenient method to do this. It lives on the Subscription object and is simply called . unsubscribe() .
When the notifier emits a value, the TakeUntil completes the Source observable. If the notifier completes without emitting any value, then the TakeUntil keeps emitting values from the source and completes when the source completes.
import { takeUntil } from 'rxjs/operators';
.pipe(takeUntil(this.destroyed$)).subscribe({YOUR_CODE})
This should help.
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