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


