Difference Between Promise and Observable Subscription
Categories:
2 minute read
Anyone who looks Promise and Observable at first it might looks like they both solve the same purpose i.e.they both used for asynchronous functionality, and immediately question arises what is the difference? which one is best? Which one I should use?
Promise
- Promise is simple and strightforward to use compare to observable
- It is a better option when you want to do something asynchrously for one time
- Code looks cleaner with async/await
Observable
- It is slightly complex to use compare with Promise however it is much more powerful than Promise
- It can be used for getting multiple responses i.e. unlike Promise it keeps the subscription alive and keep getting response whenever something available
So which one I use?
It depends on the functionality and your preference.
Promise is better in situations like getting onetime response e.g. HTTP call
e.g. angular http client respond a obserable
httpClient.get('https://example.com/api/users').subscribe(res => {
// do you logic here with res
})
// here you won't get the response.
here for whatever reason if you want process the response sequentially then it is better to use the promise as follows
const res = await httpClient.get('https://example.com/api/users/').toPromise()
// do whatever you want here with res
In this example if you use Observable you may fall into callback hell kind of situation, so Promise is a better option.
On the other hand Obervable is better choice when you want keep sending responses e.g. user login, logout events etc
e.g.
Consider you have Auth
class which takes care of your login and logout process.
class Auth {
public static authEvents$ = new Subject()
login() {
// do login process here and then publish a event
Auth.authEvents$.next('login')
}
login() {
// do logout process here and then publish a event
Auth.authEvents$.next('logout')
}}
}
You can use this in any component as
Auth.authEvents$.subscribe(event => {
if (event === 'login') {
// do something
}
if (event === 'logout') {
// do something
}
})