When a promise concludes, it either resolves (then
) or rejects (catch
). On the contrary, an observable continues to stream values until it terminates (sometimes persisting indefinitely, only ceasing when interest is lost - or unsubscribed from).
An interesting analogy can be drawn using keypress events. Using a promise for resolving/rejecting based on a keypress will only capture the "next" keypress event, requiring creation of a new promise for subsequent events.
On the other hand, with observables, creating just one instance allows continuous streaming of values until disinterest prompts unsubscription.
Promises:
const subscribeToKeyPress = () => {
let resolve;
document.addEventListener('keydown',function listener(e) {
resolve(e);
document.removeEventListener('keydown',listener); // prevent memory leaks
});
return new Promise(r => resolve = r);
}
subscribeToKeyPress().then(e => {
// completed, no further results expected
});
#####
Observables:
const subscribeToKeyPress$ = () => fromEvent(document,'keypress);
const unsubscribe = subscribeToKeyPress$().subscribe(e => {
// continuously triggered by each keypress until unsubscribed
});
unsubscribe(); // stops callback execution, avoiding memory leaks
#####
Callback Function - a basic form of "observable"
const subscribeToKeyPress = callback => {
const fn = e => callback(e); // repeated execution until unsubscribed
document.addEventListener('keypress',fn);
return () => document.removeEventListener('keypress',fn);
}
const unsubscribe = subscribeToKeyPress(e => {
// repeatedly invoked on every keypress unless unsubscribed
});
unsubscribe(); // prevents further callback calls to avoid memory leaks
How do you obtain the result from an observable as an array (similar to a promise)?
Visit https://www.learnrxjs.io/operators/utility/topromise.html for insights.
Additional information about toPromise
: https://github.com/ReactiveX/rxjs/issues/2539
If your observable never reaches completion (e.g., a keypress listener), utilizing toPromise
might not function effectively (consider pipe(take(1))
beforehand, but this complexity may overwhelm newcomers. Coming from a promise-centric background, grasping observables can pose challenges initially, though they eventually become more comprehensible with time and practice.