How to unsubscribe from an Observable returned by forkJoin?

淺唱寂寞╮ 提交于 2021-02-07 05:07:45

问题


In my Angular2-typescript app, I'm using forkJoin to return an Observable only once all the parallel HTTP calls were made.

Issue: the subscription callback keeps being executed 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 issue):

  • return an Observable in Http.service rather than a Promise
  • in my.component use .first().subscribe() instead of just subscribe()
  • put this.mySub.unsubscribe(); at the end of ngOnInit rather than inside the subscribe callback (also with setTimeout(() => ....))

回答1:


As forkJoin reference says, it

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

This means that the operator gets values from completed observables and returns a completed observable with single value. There's no need to unsubscribe from it.




回答2:


You can cancel it. Let's say observables is an array of http requests you prepared to trigger (executed via httpClient).

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

this.forkJoinSubscription.unsubscribe();

You may notice in your network tab that those requests were cancelled.



来源:https://stackoverflow.com/questions/40429666/how-to-unsubscribe-from-an-observable-returned-by-forkjoin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!