Mackelito
Mackelito

Reputation: 4421

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'?

Upvotes: 2

Views: 9907

Answers (2)

Mackelito
Mackelito

Reputation: 4421

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();
}

Upvotes: 1

Poul Kruijt
Poul Kruijt

Reputation: 71971

You can only use unsubscribe on a Subscription. You are trying to use it on a Observable.

If you use the observable inside your component using the async pipe, then you do not need to unsubscribe. This is automatically done by the framework.

If however you use it inside your component.ts, then one way is to do it like this. There are also other options, using the takeUntil pipe for instance:

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

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

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

Upvotes: 6

Related Questions