want to optimize the following code: multiple subscription in multiple if else statements.
consider:-
getList(): void {
this.subs.sink = this.subscription1.subscribe((user) => {
if (user) {
this.method1();
}
});
}
method1() {
//code
//code
if (condition){
//code
} else {
this.method2()
}
method2(){
this.subs.sink = this.subscription2.subscribe(
(response) => {
if(){
//code
} else {
this.method3();
}
}
method3(){
this.subs.sink = this.subcription3.subscribe(
(response) => {
//code
}
}
this resulting in triggering multiple subscription.
Any help. Appreciated.
There are multiple ways to streamline the multiple subscriptions. It depends what exactly the
// code
represents. If most of the// code
are same, then you could possibly usefilter
to apply the condition.The following method assumes each
// code
block is unique. It usedswitchMap
to map from one observable to another. If you do not wish to forward the observable to the subscription'snext
block, you could return RxJSEMPTY
constant. It would essentially complete the observable.