Jussi Mullo
Jussi Mullo

Reputation: 21

Wrapping Promise based JavaScript HTTP client with RxJs Observable

I was thinking of using Observables to add .flatMapLatest() & .throttle() functionality to a Promise based HTTP client library (axios). But I'm not going to change the whole application to work with Observables, so I would need something like this:

Promise -> Observable -> Promise

Anyone managed to do something like this? None of the examples I've found do exactly that.

I know that RxJs provides a way to make an Observable from Promise and then convert it back to Promise, but haven't figured out how I could apply that to multiple Promises created by random subsequent HTTP client calls.

Upvotes: 2

Views: 2195

Answers (2)

Samantha Atkins
Samantha Atkins

Reputation: 678

RXJS has a good pattern for this.

Observable.fromPromise(somePromiseReturningThing)

This is much better than the flatmap pattern above as the flatmap operates on error or legitimate return equally. Treat this obserable with your

Observable.fromPromise(aPromise)
  .map(..)
  .catch(..)

etc.

Upvotes: 0

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276506

Observables will automatically assimilate promises. You can just use them inside RxJS calls and it'll "just work":

myObservable.flatMap(x => somePromiseReturningFn("/api/" + x))

Will do exactly what you'd like it to.

Observables and promises mix and match nicely with .toPromise on observables and observables consuming promises automatically. You can safely mix and match them.

Just remember RxJS is not aware of promise library cancellation - so if you're relying on that you'd have to do it manually.

Upvotes: 1

Related Questions