Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe from an Observable returned by forkJoin?

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(() => ....))
like image 612
dragonmnl Avatar asked Nov 04 '16 18:11

dragonmnl


People also ask

How do I unsubscribe from forkJoin?

put this. mySub. unsubscribe(); at the end of ngOnInit rather than inside the subscribe callback (also with setTimeout(() => ....))

How do I unsubscribe from observable RxJS?

Unsubscribing Manually One method we can use, is to unsubscribe manually from active subscriptions when we no longer require them. RxJS provides us with a convenient method to do this. It lives on the Subscription object and is simply called . unsubscribe() .

Do I need to unsubscribe from observable in service?

🎩 Automagically Unsubscribe in Angular As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak. A memory leak occurs when a section of memory that is no longer being…


1 Answers

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.

like image 137
Estus Flask Avatar answered Sep 19 '22 07:09

Estus Flask