Amir Tugi Amir Tugi - 14 days ago 5
Javascript Question

Observable Finally on Subscribe

According to this artcle,

onComplete
and
onError
function of the
subscribe
are mutually exclusive.

Meaning either
onError
or
onComplete
events will fire up in my
subscribe
.

I have a logic block which needs to be executed whether I receive an error, or I finish my steam of information successfully.

I looked up for something like
finally
in python
, but all I found is
finally
which needs to be attached to the observable I create.

But I want to to do that logic only when I subscribe, and after the stream has ended, whether successfully or with an error.

Any ideas?

Answer

I think finally() operator is actually correct. You say:

do that logic only when I subscribe, and after the stream has ended

which is not a problem I think. You can have a single source and use finally() before subscribing to it if you want. This way you're not required to always use finally():

let source = Observable.create(observer => {
        observer.next(1);
        observer.error('error message');
        observer.next(3);
        observer.complete();
    }).publish();

source
    .finally(() => console.log('Finally callback'))
    .subscribe(
        value => console.log('#1 Next:', value),
        error => console.log('#1 Error:', error),
        () => console.log('#1 Complete')
    );

source
    .subscribe(
        value => console.log('#2 Next:', value),
        error => console.log('#2 Error:', error),
        () => console.log('#2 Complete')
    );

source.connect();

This prints to console:

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message
Comments