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?
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With