Search code examples
angularrxjsobservableunsubscribe

Observable, unsubscribe in ngOnDestroy not working


I have a dialog that opens and contains a component... in the component I do a subscription. When closing I want to unsubscribe..

private deviceObserver: Observable<BreakpointState> = this.breakpointObserver.observe([Breakpoints.XSmall]);

this.deviceObserver.subscribe(result => {
  if (result.matches) {
    this.deviceType = 'mobile';
  } else {
    this.deviceType = 'desktop';
  }
});

ngOnDestroy() {
 this.deviceObserver.unsubscribe();
}

That gives me this error:

Property 'unsubscribe' does not exist on type 'Observable'. Did you mean 'subscribe'?


Solution

  • For some reason doing the unsubscribe in ngOnDestroy broke the app... This is how I solved it:

    private deviceObserver: Observable<BreakpointState> = this.breakpointObserver.observe([Breakpoints.XSmall]);
    private breakpointObserverSubscription: Subscription;
    
    
    // in ngOnInit()
    this.breakpointObserverSubscription = this.deviceObserver.subscribe(result => {
      if (result.matches) {
        this.deviceType = 'mobile';
      } else {
        this.deviceType = 'desktop';
      }
    });
    
    public closeSearch() {
     this.onClose.apply();
     this.breakpointObserverSubscription.unsubscribe();
    }