1

In an angular project, I have a service which needs to async load a library. To ensure that methods, which use this library, don't call it before it's loaded, I created an isLoaded ReplaySubject, which doesn't emit until the library has loaded. To initially test the setup, a method looks similar to this:

  myMethod = (a: string): Observable<IPromise<Building[]>> => { //IPromise<any[]> |
return this.isLoaded.asObservable().map(() => {

    //do stuff to setup query parameters etc.

    //QT.execute returns a Promise, or rather, an object which can be cast to a promise
    return QT.execute(buildingsQuery).then(result => result);
});

};

Then, to use the results, I have to do

myMethod.subscribe(res => {res.then(...)});

Ugly.

My next step is to return just an observable, so I wrap the promise in Observable.fromPromise(), but then I'm not sure how to to just subscribe to this new inner observable. I've tried this:

myMethod = (a: string): Observable<Building[]> => {
    let bldgObs: Observable<Building[]>;
    return this.isLoaded.asObservable().map(() => {

        //do stuff to setup query parameters etc.

        bldgObs = Observable.fromPromise(QT.execute(buildingsQuery).then(result => {
            return result;
        }) as any); //have to cast as any b/c return value's .then method is not always compatible with regular promises. This has worked fine elsewhere.
    })
        .combineLatest(bldgObs, (data1, data2) => {
            return data2;
        });
};

but I never get a value. My understanding is that combineLatest, will use the calling observable (this.isLoaded.asObservable(), in this case) as the first item in the list of observables to watch.

Charlie Elverson
  • 1,180
  • 8
  • 18
  • 1
    I don't see where your `map` call is returning. Can you just change it to `flatMap` and return `Observable.fromPromise(...)`? – Pace Sep 05 '17 at 17:00
  • in the last snippet, `map` doesn't return. It just sets bldgObs. Or at least, that's the idea. I used mergeMap to return the promise and it worked like a charm. I didn't even need Observable.fromPromise(). learnrxjs.io says flatMap is an alias for mergeMap. – Charlie Elverson Sep 05 '17 at 17:19
  • Thinking a little more about this, I'm guessing `map` must have a return value, or else the observable that gets passed down the chain is empty. Is that correct? – Charlie Elverson Sep 05 '17 at 17:32
  • Yes, if you don't return anything then the outer observable will become an empty observable (`Observable` I think). – Pace Sep 05 '17 at 19:05

0 Answers0