liveBook · Manning

Unsubscribe

As explained in The Joy of JavaScript

unsubscribe is the operation that detaches a consumer from an observable or similar event source so emissions stop being delivered.

unsubscribe detaches a consumer from an observable stream or similar event source, stopping further emissions from being delivered. Calling subscribe starts a lazy Observable and returns a Subscription whose unsubscribe method controls how the producer is stopped. section 9.4.1 section 9.4.2

The operation matters because stream lifetime belongs to the subscription:

  • Retain the Subscription returned by subscribe, then call unsubscribe when the consumer no longer needs events. section 9.4.1
  • Let the producer define cleanup: an interval-backed Observable clears its setInterval identifier when unsubscribed. section 9.4.2
  • Prefer cancellation for streams that do not complete themselves; an infinite blockchain stream continues notifying subscribers until they unsubscribe. section 9.4.7

Stopping a random-number stream

A custom Observable emits a random number every second through setInterval. The subscriber receives values until some later point, when subs.unsubscribe() invokes the producer's cleanup function and clears the interval.

How The Joy of JavaScript covers it

How deep it goes
Defines a one-method Subscription interface and shows producer-specific cleanup, including interval cancellation; defers broader stream operators.
Examples
Uses a random-number interval and a reactive Blockchain whose later block emissions stop after subscription cancellation.
What it assumes
Assumes familiarity with Observable and Observer roles while defining Subscription as a minimal object with unsubscribe.
What you can do after
Operate/configure observable producers by retaining a Subscription and calling unsubscribe at the appropriate time.
How it connects
Connects Observable, Observer, Subscription, EventEmitter, and setInterval through lazy streams and producer cleanup.

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.