Skip to content

RxJS: Finally Telling Push and Pull Apart

Once you name the producer and the consumer, you see right away whether data is pulled or pushed, and you choose between function, iterator, Promise and Observable without guessing.

≈ 8 min readSoftwareReactive

RxJS: Finally Telling Push and Pull Apart

If you treat a cold Observable like a shared Promise, your HTTP request goes out as many times as someone calls subscribe. Three components on the same cold stream mean three requests – no error message, no warning, exactly as defined.

The reason has less to do with operators at first than with one question: Who decides when a value flows – the producer or the consumer? Before map, switchMap and debounceTime, people usually ask which operator is the right one. That question comes too early. Push and pull provide the basic model that cold, hot and multicasting build on later.

The one question that sorts everything#

You can describe every data source in JavaScript by its direction. There are only two.

In a pull system, the consumer actively fetches the values. It calls something and gets an answer. A function is exactly that: you call it, it delivers. An iterator is the same thing in several steps, because iterator.next() pulls out the next value. The consumer sets the pace.

In a push system, this flips. Now the producer decides when to send something, and the consumer doesn’t know in advance when the next value will arrive. A click event, a WebSocket message, a timer: all of these push as soon as they are ready. The consumer only reacts.

That sounds academic, but it has direct consequences for your code. With synchronous pull, the consumer determines the next fetch and can block while doing so; an asynchronous iterator doesn’t have to. With push, the producer decides when it delivers, and the consumer reacts to it. This is exactly where many migrations from “querying data” to “reacting to data” fail.

Four producers, two directions#

The official RxJS documentation places the four important producers in a grid. In architecture discussions, it’s the first thing I draw on the whiteboard, because afterwards most questions are already answered.

Producer Number of values Direction Evaluation
Function exactly one value Pull lazy
Iterator / Generator zero to many Pull lazy
Promise exactly one value Push eager
Observable zero to many Push lazy

Read the table as two axes. One axis asks: one value or several? The other asks: does the consumer pull or does the producer push? The Observable is the only source that pushes several values and still stays lazy. This combination makes it so powerful and so confusing for newcomers, because it has no direct counterpart in classic JavaScript.

A Promise is its closest relative, but it only covers the neighboring cell: one value, pushed, started immediately. Once you internalize this, you stop treating an Observable like a Promise with more methods.

An Observable is a function with several outputs#

Code makes this clear fastest. My introduction-rxjs material deliberately starts with the Observable constructor before it shows any operators. It forces you to name the producer and the consumer yourself.

import { Observable } from 'rxjs';

// The producer decides on its own when values flow.
const ticks$ = new Observable((observer) => {
  let n = 0;
  const id = setInterval(() => observer.next(n++), 1000);

  // Cleanup function: runs on unsubscribe or on complete.
  return () => clearInterval(id);
});

// The consumer only reacts, it does not actively pull.
const sub = ticks$.subscribe({
  next: (v) => console.log('value', v),
  error: (e) => console.error('error', e),
  complete: () => console.log('done'),
});

The block in subscribe is the observer with its three channels: next for values, error for aborting with an error, complete for a clean end. That is the complete vocabulary of a push consumer. There is nothing more, and you don’t need anything more.

For comparison, here is the same idea as a pull source. Nothing happens as long as nobody pulls.

function* naturals() {
  let n = 0;
  while (true) yield n++; // The value is produced only when pulled.
}

const it = naturals();
it.next().value; // 0  – the consumer pulls
it.next().value; // 1  – and sets the pace

Both sources deliver an infinite sequence of natural numbers. The only difference is control. With the generator, you decide with every next() when the one comes after the zero. With the Observable, the timer decides, and the values are simply delivered to you.

Lazy means: without subscribe, nothing happens#

The most consequential column of the table is “Evaluation”. The cold Observable built here is lazy. It runs its producer code only when subscribe is called, and starts over for every subscribe. Hot Observables and shared sources behave differently. A Promise, on the other hand, is eager: it starts its work the moment it is created, without any then.

This difference causes most of the mistakes when people switch over.

// eager: the request goes out immediately, even without then.
const preise = fetch('/api/preise');

// lazy: nothing happens until someone calls subscribe.
const preise$ = new Observable((observer) => {
  fetch('/api/preise')
    .then((res) => res.json())
    .then((data) => {
      observer.next(data);
      observer.complete();
    })
    .catch((err) => observer.error(err));
});

This resolves the case from the beginning. A team rebuilds a search. Before, there was a shared Promise that ran once, and several components shared its result. After the switch to an Observable, three components subscribe to the same stream. Suddenly three HTTP requests go out instead of one. Nobody made a mistake in the classic sense; the Observable behaves exactly as defined: lazy and cold, so each subscription gets its own execution. In 2017, if you wanted the Promise behavior back, you shared the stream with publishReplay and refCount or put a Subject in front of it. publishReplay is now deprecated; today shareReplay({ bufferSize: 1, refCount: true }) expresses the same intent more directly. You still have to decide on multicasting deliberately. Only when you name push, lazy and cold separately do you see why three requests happen here.

Making time visible with the marble diagram#

In push systems, everything depends on how things unfold over time, and that is exactly what makes them hard to read. A marble diagram draws this time on a line. Each marble is a pushed value, the | is complete, the X would be an error.

subscribe                         unsubscribe
   |                                   |
   v                                   v
ticks$: ---0----1----2----3----4----5--|
              (the producer pushes every 1000 ms)

The line makes two things visible right away that get lost in prose. First: the values appear according to the producer’s internal logic, here the interval, and not on demand. Second: there are two edges, the subscription and the unsubscription. The stream exists between these edges, not before and not after. Once you read marble diagrams, you stop thinking about individual values and start thinking about the lifetime of the stream.

For the direction itself, a small diagram is enough. It shows who drives whom.

flowchart LR
  subgraph Pull
    C1[Consumer] -- pulls next --> P1[Producer]
  end
  subgraph Push
    P2[Producer] -- pushes next --> C2[Consumer]
  end

The mistake almost everyone makes once#

The lazy property comes with a duty that has its own chapter in the material: Disposable. If a subscribe starts a producer, someone also has to stop it again. With ticks$ above, this is obvious: the setInterval keeps running forever as long as nobody calls unsubscribe.

const sub = ticks$.subscribe((v) => console.log(v));

// Without this line the timer ticks forever,
// even after the component is long gone.
sub.unsubscribe();

In a single-page application, this can turn into a real leak. A component subscribes to an event stream, the user navigates away, the component disappears from the DOM, but a subscription that was never ended keeps listeners and referenced objects alive. The next time the view opens, a second subscription is added, then a third. The symptoms are side effects that run twice and growing memory usage. The subscription is the boundary where a stream gets ownership and a lifetime; depending on the source, it ends through complete, error or a deliberate unsubscribe.

What remains#

Push and pull is not a theoretical detail but the grid on which you hang every decision in RxJS. Do I need one value or several? Does my consumer pull or does my producer push? Does the work start immediately or only on subscribe? And who ends the stream again? These four questions settle most operator discussions before they start.

The order in my course material – which I also use with partners like Grossweber – follows exactly this logic. First Observable, Observer and Notification, that is, the push vocabulary. Then Scheduler and Disposable, that is, time and lifetime. Operators come last, because they are only tools on top of this foundation. If you start with the list of operators, you learn vocabulary without grammar.

Further reading#

Revised and translated from German with the help of AI.