Search code examples
angularrxjsgraphqlapollo

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?


Solution

  • 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()