Unsubscribe des observables

Unsubscribe des observables

Il faut penser à unsubscribe les observables.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { interval } from 'rxjs';

const data$ = interval(1000);


const subscription = data$.subscribe({
    next: value => console.log(value),
    error: error => console.error(error),
    complete: () => console.log('DONE!')
});

// dans le ngOnDestroy()
subscription.unsubscribe();

Une façon simple de le gérer, c’est d’utiliser takeUntil

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { Component, OnInit, OnDestroy } from '@angular/core';

import { Subject, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({ ... })
export class AppComponent implements OnInit, OnDestroy {
  isOver$: Subject<boolean> = new Subject<boolean>();

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.myService.getAll()
           .pipe(takeUntil(this.isOver$))
           .subscribe(data => {
              console.info(data);
           },(e)=>{
              console.error("Error", e);
           });    
  }

  ngOnDestroy() {
    this.isOver$.next(true);
    this.isOver$.unsubscribe();
  }
}
Généré avec Hugo
Thème Stack conçu par Jimmy