Pages

Tuesday, August 16, 2022

Convert RXJS's observable to Promise and vice verse

In case you want to "mix" RXJS with promise-based approach, then firstValueForm or lastValueForm are here to rescue. Both can be imported from "rxjs" library.

See the code for converting observable to Promise. As await function can only be written inside an async function, you need to put them in a function started with the keyword async as normal.


What if you want to convert from promise to observable? Simply use "from(promise)" imported directly from "rxjs" and pass the promise as the parameter. Take a look at the following image:


The data is a promise-based one and returned from server using axios.

It is worth noting that both lastValueFrom() and firstValueFrom() can only get 1 emitted value. You might use async subscribe to get the whole data instead in case you want to use it somewhere else. Take a look at the image below:



FYI toPromise() is being deprecated in RxJS 7 and will be removed in RxJS 8