MgSam
MgSam

Reputation: 12803

Flatten Promise<Obserable<T>>

I have a function that does something like the following:

async foo() {
    await doSomething();

    return getObservableFromSomewhereElse();
}

The problem is that the await makes the signature a Promise<Observable<T>>. Because I'm already returning an Observable, I'd just like to fold the Promise into the Observable so that the signature is Observable<T>.

Note: doSomething() must occur before getObservableFromSomewhereElse().

I think Observable.defer() might help with this but I'm not certain.

Any ideas on how to make this function just return Observable<T>?

Upvotes: 3

Views: 350

Answers (1)

udalmik
udalmik

Reputation: 7988

As mentioned in comments thread - you can leave foo function as async and reuse its promise result in separate function with

async function foo() {
    await doSomething();
}

function bar() {
    return Observable
       // emits one value from resolved promise
       .fromPromise(foo())
       // maps it to your observable stream
       .flatMap(() => getObservableFromSomewhereElse());
}

Upvotes: 2

Related Questions