1
votes

I have a function that will optionally set a header with data retrieved from localStorage. The localStorage operation returns a promise that I can turn into an Observable. Once the headers are set (or not), I want to make an http request and return the Observable as a result:

let startObs;
if (useHeaders) {
  startObs = Observable.fromPromise(this.getStoredHeaders());
}
else {
  startObs = Observable.empty();
}

// wait for startObs here

return this.http.get(url, headers);

Essentially I want to wait for startObs to complete and then return the http.get Observable. I have tried using something like startObs.concat(this.http.get()) or startObs.switch(this.http.get()), but this emits from both the source observable and the http.get observable. I only want to emit the http.get Observable.

Is there any way to subscribe only to the last observable in a chain while waiting for a previous observable to complete?

2
where are you subscribing to the data? update that to postAravind
It's async, that's the whole point of observables :) So you won't be able to accomplish that the way you want. You should subscribe and do what you want in that subscribe but subscribing in a service is not a good idea either. You should simply create the observable chain, and subscribe to it from a component for examplemaxime1992
You can just use concat() then last(). reactivex.io/rxjs/class/es6/…JB Nizet

2 Answers

0
votes

You can't achieve what you want with operators like concat and switch, because you'll still be calling the this.http.get() synchronously (before your stored headers are ready). Use mergeMap instead:

return startObs.mergeMap(headers => this.http.get(url, headers));
0
votes

This looks like an easy task for concatMap:

startObs
    .concatMap(() => this.http.get(url, headers))
    .subscribe(...);

Since it's supposed to map a value using a callback function you can simply ignore the value emitted from the source startObs and just return a new Observable.

You could also chain multiple concatMap operators because they only subscribe to the next Observable when the preceding one completes.