DEV Community

Cover image for RxJS Explained: Streams That Make Async Code Simpler
The Practical Developer
The Practical Developer

Posted on Originally published at practicaldevblog.blogspot.com

RxJS Explained: Streams That Make Async Code Simpler

Quick answer

RxJS is a JavaScript library for working with asynchronous data as streams. Instead of nesting callbacks or chaining promises, you describe what should happen to each value as it arrives, using small reusable operators like map, filter, and scan.

A small clothing shop in Karachi takes orders through its website all day: an order number, an item, a price, a quantity. The shop wants a running total of the day's sales, updated as each order lands, and it wants one bad order to never kill the whole feed. Written with plain callbacks, that job turns into nested handlers and a shared total variable, with an error path that is easy to forget. Written as a stream, it reads like a list of steps: take the orders, keep the valid ones, turn each into a total, and add them up.

What is an observable, really

An observable is a source of values over time. A promise gives you one value, once, and then it is done. An observable can give you zero values, one value, or a hundred, spread across minutes. Clicks and incoming orders are natural observables: they arrive when they arrive, not when you ask.

A stream has three parts. The observable produces values. Operators transform them: map changes each value, filter drops the ones you do not want, and scan keeps a running result. The subscription consumes the result, with handlers for next, error, and complete. Nothing runs until you subscribe, which beginners miss most: without a subscriber, an observable is a plan, not a program.

What I would check before using it

My first check is whether the data actually streams. If the app makes one request and waits for one answer, a promise is simpler. RxJS pays off when values arrive repeatedly: live orders, search input, notifications, or a WebSocket feed. If nothing in the feature is live, I would leave RxJS out, as judgement.

My second check is the team's comfort with the operator vocabulary. RxJS ships with over a hundred operators, and a pipeline of six can be hard to read for someone new to them. I would keep early pipelines short, with a comment saying what the pipeline produces. If the team is small and the feature is simple, a plain event listener may serve better.

My third check is error handling, because it is where streams bite. An unhandled error ends the whole stream, as the example below shows, and a dead stream fails silently: no crash, just no more updates. I would decide up front where catchError lives and test it with a bad value on purpose.

My verdict, as judgement: use RxJS when values keep arriving and the transformations are worth naming. It flips when the work is one request and one answer.

A Karachi shop's live order stream

The demo is the shop from the intro: five orders as a stream, one with its price stored as text:

const { from, of } = require('rxjs');
const { map, filter, scan, mergeMap, catchError } = require('rxjs/operators');

const orders = [
  { id: 'ORD-1041', item: 'Lawn Suit', price: 2400, qty: 2 },
  { id: 'ORD-1042', item: 'Kurta', price: 1500, qty: 1 },
  { id: 'ORD-1043', item: 'Wool Shawl', price: 'Rs 1,800', qty: 1 },
  { id: 'ORD-1044', item: 'Cotton Shirt', price: 1200, qty: 3 },
  { id: 'ORD-1045', item: 'Dupatta', price: 900, qty: 2 },
];
Enter fullscreen mode Exit fullscreen mode

The pipeline filters out zero-quantity orders, maps each order to its line total, and uses scan to keep the running sum. The first version throws inside map when a price is not a number:

from(orders).pipe(
  filter((o) => o.qty > 0),
  map((o) => {
    if (typeof o.price !== 'number') {
      throw new Error('Bad price for ' + o.id + ': ' + o.price);
    }
    return { id: o.id, item: o.item, total: o.price * o.qty };
  }),
  scan((running, o) => running + o.total, 0)
).subscribe({
  next: (running) => console.log('Running total: Rs ' + running),
  error: (err) => console.log('STREAM FAILED: ' + err.message),
  complete: () => console.log('All orders processed.'),
});
Enter fullscreen mode Exit fullscreen mode

The actual output:

Running total: Rs 4800
Running total: Rs 6300
STREAM FAILED: Bad price for ORD-1043: Rs 1,800
Enter fullscreen mode Exit fullscreen mode

The first two orders processed fine: 2400 times 2 is 4800, plus 1500 is 6300. Then the Wool Shawl arrived with its price as the string "Rs 1,800", the map threw, and the stream ended. Orders 1044 and 1045 never ran: in RxJS, an error in the pipeline terminates the stream, and everything after the bad value is lost.

The fix is to catch the error per order, not per stream: wrap each order in mergeMap with its own catchError, so one bad order is logged and skipped:

from(orders).pipe(
  filter((o) => o.qty > 0),
  mergeMap((o) =>
    of(o).pipe(
      map((order) => {
        if (typeof order.price !== 'number') {
          throw new Error('Bad price for ' + order.id + ': ' + order.price);
        }
        return { id: order.id, item: order.item, total: order.price * order.qty };
      }),
      catchError((err) => {
        console.log('Skipped bad order: ' + err.message);
        return of(null);
      })
    )
  ),
  filter((o) => o !== null),
  scan((running, o) => running + o.total, 0)
).subscribe({
  next: (running) => console.log('Running total: Rs ' + running),
  error: (err) => console.log('STREAM FAILED: ' + err.message),
  complete: () => console.log('All orders processed.'),
});
Enter fullscreen mode Exit fullscreen mode

After the fix:

Running total: Rs 4800
Running total: Rs 6300
Skipped bad order: Bad price for ORD-1043: Rs 1,800
Running total: Rs 9900
Running total: Rs 11700
All orders processed.
Enter fullscreen mode Exit fullscreen mode

The bad order is logged and skipped, the totals reach 9900 and then 11700, and the stream completes. The lesson is placement: catchError at the end of the pipeline still ends the stream, while catchError inside mergeMap lets it live on.

Terminal output of an RxJS order stream: the first run stops at a bad price, and the fixed run skips it and ends at Rs 11,700.

Common mistakes and how to fix them

First, forgetting to subscribe. You build a pipeline, run the program, and nothing happens. No error, nothing. Observables are lazy: nothing runs until subscribe is called. The fix is to subscribe and keep the subscription, so you can unsubscribe later.

Second, catching errors in the wrong place. A catchError at the end of the pipe logs the failure, but the stream still ends, so later values never arrive. The fix, shown above, is to catch inside mergeMap, return a fallback like of(null), and filter it out.

Third, using map for work that returns another observable. You get a stream of streams, and the subscriber sees observable objects instead of values. The fix is mergeMap, switchMap, or concatMap, which flatten the inner stream. Pick switchMap when only the latest request matters, and concatMap when order matters.

Fourth, never unsubscribing. A component leaves the page, but its subscription keeps firing, holding memory and updating state that no longer exists. The fix is to call unsubscribe in the cleanup step, or use takeUntil with a notifier that fires when the component goes away.

Frequently Asked Questions

Is RxJS only for Angular? No. RxJS is standalone; Angular just uses it heavily, which is where most developers meet it. The code here runs in plain Node.js, and RxJS works in React and Vue too.

When should I choose RxJS over promises? Choose promises for a single value, like one HTTP request, and RxJS when values arrive over time: user input, live updates, a queue of events. The JavaScript async/await post covers the promise side in detail. If you are nesting callbacks to handle repeated values, a stream has started to earn its keep.

What is the difference between map and mergeMap? Map turns each value into another value; mergeMap turns each value into another observable and flattens it into the main stream. Use map for simple conversions like price times quantity, and mergeMap when each value triggers its own async work.

What to remember

  • An observable is values over time; nothing runs until you subscribe.
  • Operators like map, filter, and scan transform values; the subscription consumes them.
  • An unhandled error ends the stream, so catch bad values per item with catchError inside mergeMap.
  • Use promises for one-off work and streams for values that keep arriving.
  • Unsubscribe from long-lived streams, or they keep running after their page is gone.

Where this leaves you

The shop's order feed now survives its own bad data. One text price no longer costs the shop the rest of the day's orders, and the running total is a short pipeline anyone can read instead of a tangle of callbacks. Try it on something small you already own: a search box that debounces input, or a list that updates as events arrive. Build the pipeline, feed it one bad value on purpose, and watch whether the stream survives. That one test tells you more about RxJS than any list of operators.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Originally published at https://practicaldevblog.blogspot.com/2026/12/rxjs-explained-streams-async.html

Top comments (0)