1

I want to fork multiple http requests into one observable, call it by interval and share same data between all subscribers.

My code looks like this so far:

import {Observable} from "rxjs/Rx";

let obs = Observable
    .interval(10000)
    .publish()
    .connect()
    .forkJoin(
      this.http.get(API_URL + "x", {headers: this.headers})
        .map(response => response.json()),
      this.http.get(API_URL + "y", {headers: this.headers})
        .map(response => response.json())
    )
    .map(res => {
     // do some stuff
     return res;
    });

Error:

Typescript Error
Property 'forkJoin' does not exist on type 'Subscription'.

I've read:

https://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html

Multiple $http requests in Ionic2

http://restlet.com/blog/2016/04/12/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-2/

Thanks!

kaynow
  • 27
  • 6
  • did you try without `publish()` and `connect()`? – chrigu Jan 25 '17 at 09:00
  • Results into this error: Property 'forkJoin' does not exist on type 'Observable'. – kaynow Jan 25 '17 at 09:08
  • at least you have an Observable instead of a Subscription. Maybe you'll find an answer in http://stackoverflow.com/questions/38443798/property-forkjoin-does-not-exist-on-type-typeof-observable-angular2 – chrigu Jan 25 '17 at 09:22
  • I tried all hints given in that link but nothing helped. I tried to update to rxjs 5.0.3 but same result. Reverting to 5.0.0-beta.12 – kaynow Jan 25 '17 at 09:34
  • `forkJoin` is a static Observable method... You should call it with `Rx.Observable.forkJoin(...)` – olivarra1 Jan 25 '17 at 10:49

1 Answers1

2

Something like this should work:

let source = Observable
    .interval(1000)
    .flatMap(() => {
        return Rx.Observable.forkJoin(
            this.http.get(API_URL + "x", {headers: this.headers})
                .map(response => response.json()),
            this.http.get(API_URL + "y", {headers: this.headers})
                .map(response => response.json())
        )
    })
    .publish();

source.connect();

Then Observers subscribe to this observable

source.subscribe(...);

What I'm doing here is to take the interval observable and replace each value for a forkJoin of all operations. Then publishing it to share the same data to many subscriptions.

Another issue you had in your implementation is that you were returning the Subscription from .connect(), that's just meant to dispose it (unsubscribe) whenever you need it. Observers should subscribe to the published source.

olivarra1
  • 3,269
  • 3
  • 23
  • 34
  • Thank you! It's working! In my case, I had to replace "Rx.Observable.forkJoin" with "Observable.forkJoin". Thanks for the great explanation ;) – kaynow Jan 25 '17 at 13:57