liveBook · Manning

Subscribe

As explained in The Joy of JavaScript

subscribe is the operation that attaches a consumer to an observable or similar event source so emissions are delivered to that consumer.

subscribe attaches an observer to an Observable so emitted values reach its callbacks. Observables are lazy: subscribing starts the producer, while the returned Subscription controls later cancellation. section 9.4.1 section 9.4.2

A subscription commonly coordinates these behaviors:

  • Handle emissions with next, optionally handling failures with error and termination with complete. section 9.4.1
  • Start deferred work when subscribe is called, such as interval-based random-number generation. section 9.4.2
  • Stop ongoing delivery with unsubscribe; custom cleanup can clear timers or detach event listeners. section 9.4.2
  • Receive both existing and future values when subscribing to an object exposed through Observable.from. section 9.4.7

Subscribe to a live random-number stream

const subs = randomNum$.subscribe({ next(number) { console.log('New random number:', number); }, complete() { console.log('Stream ended'); } }); // later subs.unsubscribe(); The Observable remains inert until subscribe starts its interval; unsubscribe invokes the producer's cleanup. section 9.4.2

Listing 9.17 Using observables to emit random numbers
function newRandom(min, max) {                             #1
   return Math.floor(Math.random() * (max - min)) + min;
}
 
const randomNum$ = new Observable(observer => {            #2
   const _id = setInterval(() => {
      observer.next(newRandom(1, 10));
   }, 1_000);
 
   return() => {                                           #3
      clearInterval(_id);
   };
})
 
const subs = randomNum$
    .subscribe({
       next(number) {
          console.log('New random number:', number);
       },
       complete() {
          console.log('Stream ended');
       }
    });
 
 // some time later...
 
 subs.unsubscribe(); 

Inspect the complete custom Observable example, including emission, callback handling, and timer cancellation. section 9.4.2

How The Joy of JavaScript covers it

How deep it goes
Defines callback handling and cancellation, then demonstrates producer cleanup; it stops short of a full operator library.
Examples
Uses random numbers, observable-lifted pairs, and a reactive blockchain that delivers existing and newly pushed blocks.
What it assumes
Assumes JavaScript callbacks and iterable familiarity while defining Observable, Observer, and Subscription as foundational stream roles.
What you can do after
Operate/configure streams by registering next, error, and complete handlers and unsubscribing when delivery is no longer needed.
How it connects
Connects Observable, Observer, Subscription, Observable.from, operators, iterables, and Symbol.observable.

Also explained in

Compare how 3 books explain subscribe →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.