I would like to use the RXJS Observable. Basically it works fine, but I need not just to react when observer.next() but also when observer.complete() is called. How do I get the event of OnComplete of an RXJS Observable? In my opinion the RXJS doc is confusing.
export class Service {
myMethod():Observable<any> {
return Observable.create((observer:any) => {
for(let i=0; i<10; i++) {
observer.next(i);
}
if(true==true) {
// this event I need
observer.complete();
} else {
observer.error(xhr.response);
}
}
}
export class Component() {
// constructor etc.
doSome() {
this.service.myMethod()
// Here I would like to get OnComplete event
.catch(this.handleError)
.subscribe((num:any) => {
console.log(num);
});
}
}
The subscribe method accepts three callbacks. The last one is for the complete event.
You could also leverage the
finally
operator for this.note: there is a difference between the two examples in case we have errors: if we would add
console.log
s we would see that in the first case onlyhandleError
is printedin the second case
in other words
finally
is always called, werecomplete
is not.As Thierry Templier answered one option is to leverage the
finally
/finalize
(rxjs docs) (but it's not the same as using thecomplete
event, see the notes)last
Another option to do something on complete is
last
(rxjs/last)