Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  30] [ 2]  / answers: 1 / hits: 160197  / 8 Years ago, sun, november 20, 2016, 12:00:00

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?


More From » rxjs

 Answers
5

The current pipable variant of this operator is called finalize() (since RxJS 6). The older and now deprecated patch operator was called finally() (until RxJS 5.5).



I think finalize() 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 finalize() before subscribing to it if you want. This way you're not required to always use finalize():



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

source.pipe(
finalize(() => 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


Jan 2019: Updated for RxJS 6


[#59992] Thursday, November 17, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skylerselenem

Total Points: 282
Total Questions: 101
Total Answers: 107

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;