Discover why waiting once is old news and listening continuously is the future!
Observable vs Promise mental model in Angular - When to Use Which
Imagine you want to get data from a server and update your app whenever new data arrives, like watching a live sports score.
Using simple callbacks or promises means you only get one update and then you have to set everything up again manually for new data. This is tiring and easy to mess up.
Observables let you listen to a stream of data over time, so your app updates automatically whenever new data comes in, without extra setup.
fetch(url).then(response => response.json()).then(data => console.log(data)); // one-time fetch
observable$.subscribe(data => console.log(data)); // continuous updates
You can handle multiple data events smoothly, like live chats, real-time notifications, or streaming data.
Think of a news app that shows breaking news instantly as reporters send updates, without you refreshing the page.
Promises handle one-time async results; Observables handle streams of data.
Observables make real-time updates easy and clean.
Using Observables fits well with Angular's reactive style.
Practice
Observable and a Promise in Angular?Solution
Step 1: Understand the nature of Promise
APromiserepresents a single future value or error that will be resolved once.Step 2: Understand the nature of Observable
AnObservablecan emit multiple values over time and can be stopped or cancelled.Final Answer:
Promisehandles a single future value;Observablecan handle multiple values over time. -> Option BQuick Check:
Promise = single value, Observable = multiple values [OK]
- Thinking Promise can emit multiple values
- Believing Observable cannot be cancelled
- Confusing synchronous and asynchronous behavior
Solution
Step 1: Check Promise constructor syntax
The Promise constructor takes a function with two parameters:resolveandreject.Step 2: Verify correct usage to resolve with 42
Callingresolve(42)inside the function correctly resolves the Promise with 42.Final Answer:
const p = new Promise((resolve, reject) => resolve(42)); -> Option CQuick Check:
Promise constructor needs resolve and reject parameters [OK]
- Omitting reject parameter in Promise constructor
- Calling reject instead of resolve to return value
- Returning value directly without resolve
const obs = new Observable(subscriber => {
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
});
obs.subscribe(value => console.log(value));What will be printed to the console?
Solution
Step 1: Analyze Observable emissions
The Observable emits two values: 1 and 2, then completes.Step 2: Understand subscription behavior
The subscriber logs each emitted value, so both 1 and 2 are printed.Final Answer:
1 2 -> Option AQuick Check:
Observable emits multiple values, all logged [OK]
- Assuming only first value is logged
- Thinking complete() emits a value
- Confusing Observable with Promise single value
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('done'), 1000);
});
p.then(result => console.log(result));
p.catch(error => console.error(error));
p.cancel();Solution
Step 1: Check Promise API for cancellation
Promises do not support cancellation; there is no cancel() method.Step 2: Identify error cause
Callingp.cancel()will cause a runtime error because cancel() is undefined.Final Answer:
Promises do not have a cancel() method, so calling it causes an error. -> Option AQuick Check:
Promise cancellation is not supported [OK]
- Thinking Promise supports cancel() like Observable
- Confusing resolve and reject usage
- Believing then() must come after catch()
Solution
Step 1: Identify need for multiple values over time
Fetching user data every 5 seconds means multiple values over time, which suits an Observable.Step 2: Understand cancellation requirement
Observables can be unsubscribed to stop receiving updates, fitting the need to stop on navigation.Final Answer:
Use an Observable that emits new user data every 5 seconds and unsubscribe on navigation. -> Option DQuick Check:
Multiple updates + cancel = Observable with unsubscribe [OK]
- Using Promise for multiple repeated values
- Assuming Promise supports cancel()
- Not unsubscribing Observable causing memory leaks
Ready to prove it?
Pass the test and this pattern moves unknown
