Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you unsubscribe to apollo observable in angular?

I'm building an angular (4.x) application using apollo-angular, and I'm wondering how to unsubscribe from apollo observables (if you need to at all).

I'm trying to follow the guidance in this response by creating a query:

this.query = this.apollo.watchQuery<LatestReportQueryResponse>({
  fetchPolicy: 'network-only',
  query: myQuery
});

Assigning a new subject:

  private ngUnsubscribe: Subject<void> = new Subject<void>();

Subscribing to the query:

this.query.takeUntil(this.ngUnsubscribe).subscribe(({ data }) => {...}

and then destroying all active observables on a onDestroy event cycle with something like:

ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

After adding the .takeUntil(this.ngUnsubscribe), I run into lint errors like:

Argument of type 'Subject' is not assignable to parameter of type 'Observable'.

Or when I try to manually unsubscribe to the ApolloQueryObservable, I get:

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

Is unsubscribing necessary for apollo observables?

like image 900
Tkwon123 Avatar asked Sep 05 '17 20:09

Tkwon123


2 Answers

The return value of this.query.takeUntil(this.ngUnsubscribe).subscribe(...) should give you the unsubscribe function.

subscribe and save unsubscribe function:

this.unsubscribe = this.query.takeUntil(this.ngUnsubscribe).subscribe(...)

on the onDestroy event cycle, call the function:

this.unsubscribe()

like image 133
Locco0_0 Avatar answered Oct 10 '22 01:10

Locco0_0


Although the question is answering this is a more specific scenario that explains more to this question, so adding this below blog link here. https://www.digitalocean.com/community/tutorials/angular-takeuntil-rxjs-unsubscribe

like image 20
Titus Vimal Raj Avatar answered Oct 10 '22 00:10

Titus Vimal Raj