Home > Back-end >  How to convert Promise<Observable<T>> to Observable<T>?
How to convert Promise<Observable<T>> to Observable<T>?

Time:10-13

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);

CodePudding user response:

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))
  );
}
  • Related