I'm relatively new to RXJS so I apologize if this is a repeat. I tried searching for answers but wasn't able to find any, potentially because I don't know which search terms to use.
I'm trying to understand how I can know when the finalize block of a service call completes, because it updates a shared state variable.
Here is the stackblitz of it, though I'll also post snippets below: https://stackblitz.com/edit/angular-ivy-xzvkjl
I have an Angular application with a service that sets a shared isLoading flag to true, kicks off an HTTP request, then uses finalize to set the isLoading flag back to false, so that regardless of success or error, the items that check the isLoading flag know that the HTTP request is no longer processing.
I've simplified that scenario into separate methods instead of separate classes:
isLoading = false;
public ngOnInit() {
this.serviceCall().subscribe(
next => {
console.log("value of isLoading in next handler: " + this.isLoading);
},
err => {
console.log("value of isLoading in error handler: " + this.isLoading);
},
() => {
console.log("value of isLoading in complete handler: " + this.isLoading);
}
);
}
private serviceCall() {
this.isLoading = true;
return this.httpCall().pipe(
tap(value => console.log(value)),
finalize(() => {
this.isLoading = false;
console.log("Value of isLoading in serviceCall finalize: " + this.isLoading);
})
);
}
private httpCall() {
return new Observable(subscriber => {
console.log("Starting emissions");
subscriber.next(42);
subscriber.next(100);
subscriber.next(200);
console.log("Completing emissions");
subscriber.complete();
});
}
I was surprised to find that the output of this example is
Starting emissions
42
value of isLoading in next handler: true
100
value of isLoading in next handler: true
200
value of isLoading in next handler: true
Completing emissions
value of isLoading in complete handler: true
Value of isLoading in serviceCall finalize: false
Why is the finalize of the serviceCall invoked AFTER the complete handler of the ngOnInit's subscribe block? And how am I supposed to know when the serviceCall has completed its manipulation of the shared variable if not through a completed handler?