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.
