user1907849
user1907849

Reputation: 990

Using Promise inside a Observable

Since inside a Observable we have an option of calling Promise ,I have a clarification regrading this.

Since a promise gets executed immediately after declaration , will it be executed without attaching Subscribe method to it ? And also since it cannot be cancelled why would anyone think of calling a Promise inside a observable .

Rx.Observable.fromPromise():

const computeFutureValue = new Promise((resolve, reject) => {
//make http api call
});

Rx.Observable.fromPromise(computeFutureValue)
.subscribe(
val => {
console.log(val);
},
err => {
console.log(`Error occurred: ${err}`);
},
() => {
console.log('All done!');
});

Upvotes: 2

Views: 1749

Answers (1)

frido
frido

Reputation: 14139

As you said, a Promises body is executed when you create the Promise. So when you create this Promise:

const computeFutureValue = new Promise((resolve, reject) => {
  //make http api call
});

the http request is executed no matter what you do next. Using from (or fromPromise) to convert the Promise to an Observable and subscribing to this Observable doesn't affect the Promise and it's execution in any way.

You'd want to convert a Promise to an Observable if you want to be able to work with all the operators Observables offer or because your app works with and requires Observables at certain points.

If you only want to create and execute a Promise when you subscribe to an Observable you can use defer, see my answer here: Convert Promise to Observable

Upvotes: 4

Related Questions