How to unsubscribe from Observable returned by forkJoin?

In my Angular2 - typescript application, I use forkJoin to return an Observable only after all concurrent HTTP calls have been made.

Problem : Subscription callback continues to run indefinitely

Here is my code:

http.service

import {Http} from "@angular/http"; constructor (private _http: HTTP) {} makeGetRequest(....) { return this._http.get(URL) .map (res => res.json) .toPromise(); 

my.service

 import {Observable} from "rxjs/Observable"; import {HttpService} from "http.service" constructor (private _httpService: HttpService) {} myMethod(): Observable<any[]> { return Observable.forkJoin( this._httpService.makeGetRequest( URL1 ), this._httpService.makeGetRequest( URL2 ) ) } 

my.component

 import MyService from "my.service"; import Subscription from "rxjs"; constructor (private _service: MyService) {} mySub: Subscription; ngOnInit() { this.mySub = this._service.myMethod.subscribe(data => { data.forEach(console.log(data)); this.mySub.unsubscribe(); } } 

What I tried (same problem):

  • return Observable to Http.service, not Promise
  • in my.component use .first (). subscribe () instead of just subscribing ()
  • put this.mySub.unsubscribe (); at the end of ngOnInit, and not inside the subscription callback (also with setTimeout (() => ....))
+7
source share
3 answers

As forkJoin link says, it

Runs all observable sequences in parallel and collects their last elements.

This means that the operator receives values ​​from completed observables and returns completed observables with a single value. No need to unsubscribe from it.

+20
source

You can undo it. Let's say, say, observables is an array of http-requests that you prepared to run (they are executed through httpClient ).

 this.forkJoinSubscription = forkJoin(observables).subscribe(responses => { . . . do something }); this.forkJoinSubscription.unsubscribe(); 

You may notice on your network tab that these requests have been canceled.

0
source

Unsubscribe with the ngOnDestroy lifecycle hook. If we do not unsubscribe from the Observable when the component is destroyed, we will leave memory leaks. If you remove .unsubscribe () in a working demo, you will see this when * ngIf removes the component. In our subsequent examples, we will see how Angular can help us manage our Rx subscriptions.

0
source

Source: https://habr.com/ru/post/1259297/


All Articles