RxJS - observable doesn't complete when an error occurs RxJS - observable doesn't complete when an error occurs javascript javascript

RxJS - observable doesn't complete when an error occurs


That's because an error means completion, so the callback associated to onCompleted never gets called. You can review here Rxjs contract for observables (http://reactivex.io/documentation/contract.html) :

An Observable may make zero or more OnNext notifications, each representing a single emitted item, and it may then follow those emission notifications by either an OnCompleted or an OnError notification, but not both. Upon issuing an OnCompleted or OnError notification, it may not thereafter issue any further notifications.`

For error management, you can have a look at :https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/errors.md


Another and probably the simplest solution might be using the add() function.
The statement will be always executed regardless an erroroccured or not (like the finally statement in most programming languages).

observer.subscribe(    function(x) { console.log('succeeded with ' + x ) },    function(x) { console.log('errored with ' + x ) },    function() { console.log('completed') }).add(() => {    console.log("Will be executed on both success or error of the previous subscription"));


While I was having the same question, I bumped into this github issue.

Apparently finally method of Observable object needs to be used in this case.

Quoting from Aleksandr-Leotech from that thread:

Complete and finally are totally different things. Complete means that the observable steam was finished successfully. Because you can have many success calls. Finally means that steam has ended, either successfully or not.

It is not obvious with HTTP requests, but imagine two additional scenarios.

  1. Mouse events. You will be receiving a never-ending steam of success callbacks, but you will never receive finally or complete, because user events will never stop (unless you trigger an exception with buggy code, then you will get error and finally).

  2. Working with web sockets. You will get multiple success callbacks, but at some point in time your communication with back end will stop and you will get both complete and finally unless you have some errors, which will call error and finally.

So, you might be getting multiple or no success calls, zero or one error call, zero or one complete and zero or one finally.