Promise vs Observable difference
Promise
- It resolves or reject a single value and can handle a single value async task at a time.
- A promise once resolved the async value it completes, can no longer be used.its just one-time use and here it falls short.
- Not cancellable
-
No rxjs support for operators.
read more about promise
Observable
- ability to emit multiple asynchronous values.
- Used to handle the stream of events or values. Consider you have an array of numerous tasks or values, and you want every time value is inserted into this it should be handled automatically. Anytime you push a value into this array, all of its subscribers will receive the latest value automatically.
- Observables are useful for observing input changes, repeated interval, broadcast values to all child components, web socket push notifications etc.
- Can be canceled using the unsubscribe method anytime.
- One more last good part that promise that has is support for rxjs operators. You have many pipe operators majorly map, filter, switchMap, combine latest etc. to transform observable data before subscribing.
operation | observables | Promise | ||||
---|---|---|---|---|---|---|
creation |
const obs= new Observable((observer) => { observer.next(5); });
|
const promise= new Promise((resolve) => { resolve(5); }); |
||||
Subscribe |
|
|
||||
unsubscribe |
| no cancellable |
Comments
Post a Comment