user7308733
user7308733

Reputation:

Rxjs - Call promise and observable sequentially

I want to call a function that will return a promise and then pass the result to another function that will return an observable. I need to do this sequentially and get the final result as an observable so I can subscribe.

For example:

// Call a function and return a Promise
myPromise() {}

// Make an http call and return an Observable
myObservable() {}

// Call myPromise() then call myObservable() and return
// an Observable with the result
// *I don't know how this function should be*
myFunction() {}

// Subscription
myFunction().subscribe(
  result => console.log(result),
  error => console.log(error),
  () => console.log('completed'));

How can I do this?

Upvotes: 2

Views: 581

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16882

You could do the following:

let stream$ = Observable.defer(() => Observable.fromPromise(myPromise()))
    .flatMap(promiseResult => myObservable(promiseResult));

stream$.subscribe(obsResult => console.log(obsResult));

The .defer is needed to ensure that your promise-method is called with every subscribe, and not just once during initialization.

Upvotes: 2

Related Questions