BACK
Lessons2. Push vs Pull and lazy execution
Lessons · 02

2. Push vs Pull and lazy execution

Two ways to get a value

Before going deeper into RxJS, there's one key idea to nail down: who decides when a value appears? There are two answers — Pull and Push.

Pull: the consumer pulls

Pull is when you ask for a value and get it right away. The classic example is a plain function:

const value = getValue(); // you chose the moment

Here the consumer is in charge. The source is passive — it just hands over a value when asked.

Push: the source sends

Push is the opposite: the source decides when to send a value, and the subscriber simply waits. Think of email — the mail carrier drops letters in your box as they arrive.

An Observable is a Push system. Once you subscribe, values reach you whenever the source emits them.

Observables are lazy

This rule is important enough to memorize on its own: an Observable does nothing until you subscribe. When you write new Observable(fn), the function fn is merely stored. It runs only at the moment of .subscribe().

That's a big contrast with a Promise: a Promise starts its work the instant it's created, whether or not anyone is listening. An Observable is the reverse — it stays quiet until something "switches it on."

Glossary

  • new Observable(fn) — creating an Observable by hand. fn is the "recipe" function describing what to do once someone subscribes.
  • subscriber — the object handed to the recipe function. It has a next(value) method you use to push values to the subscriber.

Your task

  1. Inside new Observable(subscriber => { ... }), make the first line console.log('Observable started'). That confirms the recipe code ran.
  2. Right after it, call subscriber.next('Value') — that sends the string 'Value' to the subscriber.
  3. The Before subscribe and After subscribe logs are already there. Leave them — they let you see the order.
  4. Run it and watch the order: Before subscribe → Observable started → Received: Value → After subscribe. That order proves the Observable started exactly on subscribe.
Solution spoiler · click to reveal
const { Observable } = Rx;

const stream$ = new Observable(subscriber => {
  console.log('Observable started');
  subscriber.next('Value');
});

console.log('Before subscribe');

stream$.subscribe(value => {
  console.log('Received: ' + value);
});

console.log('After subscribe');
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...