In my Angular project, I came into one case as following:
In the Frontend side I have a language system, user can choose one language from the options. And each time user choose a new language I need to invoke a server side method subscribe
with it, and if the invoke run successfully, it will return to a subscriptionid
.
Next time, when user change a new language, I need to create a new subscription. But before that, I need to unsubscribe
the current one. The demo code goes as following:
this.start().subscribe((res) => {
// store current subscription id
this.currentSubscriptionId = res.SubscriptionId;
});
private start(): Observable<{ [key: string]: string }> {
return this.xService.language$.pipe(
switchMap((language) =>
this.unsubscribe().pipe(
switchMap((_) => this.invoke("subscribe",language)) // this.invoke return observable<any>
)
)
);
}
private unsubscribe(): Observable<any> {
if (this.currentSubscriptionId) { // default initial value is empty string ""
return this.invoke("Unsubscribe", {
Id: this.currentSubscriptionId
});
} else {
return of("");
}
}
so i use a state variable currentSubscriptionId
for this flow. It's default value is empty string, so for the first time, no need to invoke the unsubscribe
method, return an of
observable.
in the current implementation, I capsulate the logic inside function of unsubscribe
and based on the state variable currentSubscriptionId
to handle the flow.
is there any other optimized solution for this case? do this kind of judgement control in a more RxJS style.