This article follows on from my previous articles startWith and flatMap vs switchMap**.**

I like writing about RxJS. Even though I’ve spent so much time with it lately with my active projects, I still find new and exciting features that improve my development workflow.

Whilst building a new PWA that we’re working on at Intoware, I found a need to blend together RxJS Observables and JavaScript Promises. Here’s what I found out.

TLDR;

Use the from() Observable to wrap your promises and then you can use them in an RxJS pipeline.

Read on if you’d like to know the details.


Reactive Programming?

Before we dive in deep, some quick concepts. The core principles of Reactive Programming involve subscribing to a stream of data.

Before Reactive Programming, you would request the data you needed (perhaps a stock price) and then on a timer perhaps ask for it again.

However, now, you can “subscribe” to a stream which will emit when new data is available. Much easier.

Libraries like RxJS allow the easy creation and subscription of data streams. In addition, Operators will alter the stream in different ways to create a data pipeline.

Examples of Operators could be:

  • Filter — Only process the stream is certain conditions pass
  • Throttle — Restrict in a time-based manner the data that is being emitted (usually to help with UI bottlenecks)
  • Map — Transform the data from the stream (expose properties or perform calculations)

Operators and Observables are tied together in some really interesting ways. A simple example could be:

Fetch me the latest stock ticker symbols, updating no more than once per minute

This would be achieved by:

  • Creating an Interval Observable that emits every 60 seconds
  • Switching to a GET request to fetch the stock data
  • Add the “ShareReplay” Operator to serve the same data for multiple subscribers in the future

#reactive-programming #rxjs #asyncawait #javascript-development

RxJS Tips — Promises Into Observables
1.10 GEEK