Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS Migration 5 to 6 - Unsubscribe with TakeUntil

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.

like image 970
Juri Avatar asked May 30 '18 14:05

Juri


People also ask

Does takeUntil unsubscribe?

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.

What is takeUntil operator in RxJS?

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.

How do I unsubscribe from RxJS?

Unsubscribing Manually RxJS provides us with a convenient method to do this. It lives on the Subscription object and is simply called . unsubscribe() .

Does takeUntil complete the observable?

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.


1 Answers

import { takeUntil } from 'rxjs/operators';

.pipe(takeUntil(this.destroyed$)).subscribe({YOUR_CODE})

This should help.

like image 97
Paresh Varde Avatar answered Sep 20 '22 05:09

Paresh Varde