We're using RxJs 7.4 and I'm wondering if there is a finalizer with the new .subscribe() syntax?
I will often have code such as:
this.service
.someMethod()
.subscribe({
next: () => {
nextThings();
this.someBool = false;
},
error: err => {
errorThings();
this.someBool = false;
}
});
Is there a finalizer equivalent with this new next/error syntax so I only have to set someBool in one place?
CodePudding user response:
Yes, take look at pipeable operators. finalize is what you looking for.
sample:
this.service
.someMethod()
.pipe(
finalize(() => this.someBool = false))
.subscribe({
next: () => {
nextThings();
//not need this.someBool = false;
},
error: err => {
errorThings();
//not need this.someBool = false;
}
});```
CodePudding user response:
If I understand right your question, I would start saying that next is part of a "finalizer" only if this.service.someMethod() returns an Observable which notifies only once and then completes.
This is the case with Observables that map http calls, but not true in general terms.
In any case, as it has been already pointed in other responses, you can use the finalize operator if you want to execute one function when the Observable either errors or completes.
Otherwise you can use the complete property of the Observer to run some logic when the Observable completes, like this
this.service
.someMethod()
.subscribe({
next: () => {
nextThings();
},
error: err => {
errorThings();
},
complete: () => {
// completeThings()
}
});
this does not solve the repetition of the logic, but is more accurate in terms of "finalizer".
