How to convert Promise<Observable<T>> to Observable<T>?

I have this function:

someFunction(): Promise<Observable<boolean>> {
  return Promise1()
           .then(text => Promise2(text))
           .then(resultString => Observable(resultString))

Where Promise1 and Promise2 are functions that return promises and Observable is a function that returns an observable.

So to get an observable value I have to do the next call:

someFunction().then(res => res.subscribe(value => //get Value));

Is there a way to change someFunction to get the value directly from an observable?

someFunction().subscribe(res => //getValue);

1 answer

  • answered 2021-10-12 16:07 Mrk Sef

    Try something like this?

    • from converts a promise to an observable
    • switchMap does this conversion as well, so you can just return a promise from within that lambda
    someFunction(): Observable<boolean> {
      return from(promise1()).pipe(
        switchMap(text => promise2(text)),
        switchMap(resultString => observable1(resultString))

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum