Http Subscription on RxJs : not to use complete as a finally substitute
Prayatna Bhattarai
Posted on March 16, 2021
Coming from the promise
land, I was never aware of how .finally
was substituted when subscribed to an observable.
The easy way of how I was using was to add it on complete
the third param
of subscribe
BUT whenever an error occurs on the http
request the subscribe
never calls the complete method
You can find more info here and here
To use finally like we do when dealing with Promises
, we can use finalize
operator and pipe it through the observable$
like this
this.someService.fetchDataFromApi()
.pipe(
finalize(() => {
this.isBusy = false;
}).subscribe(()=>{
// next
}, () => {
// error
}, () => {
// complete
});
I did have a look of another easier method - to add a function at the end of subscription
by using .add()
but it is actually used to add a teardown method on the subscription
or add more subscription/child to your existing subscription
. So the better way would be to use finalize
as illustrated on the code above.
If you find other ways then please do share it :)
Posted on March 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.