8

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
Juri
  • 1,531
  • 2
  • 20
  • 43

2 Answers2

10
import { takeUntil } from 'rxjs/operators';

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

This should help.

Paresh Varde
  • 1,084
  • 3
  • 16
  • 39
-3
this.ngUnsubscribe.complete();

To

this.ngUnsubscribe.unsubscribe();
Taha Zgued
  • 1,088
  • 12
  • 18
  • 4
    i don't think this is correct. This are two different ways to unsubscribe https://blog.codecentric.de/en/2018/01/different-ways-unsubscribing-rxjs-observables-angular/ – Juri Jul 10 '18 at 07:55