An arrow function is an object just like almost anything else in JS. You don't have to pass them inline, but can store them in a variable and pass that to your function instead.
From the initial code using inline functions:
if(condition1) {
asyncFun1().subscribe((result) => {
commonCode
})
} else {
asyncFun2().subscribe((result) => {
commongcode
})
}
you can extract them to variables:
if(condition1) {
const callback = (result) => {
commonCode
};
asyncFun1().subscribe(callback);
} else {
const callback = (result) => {
commonCode
};
asyncFun2().subscribe(callback);
}
And in the next step, move the shared statements out of the conditional:
const callback = (result) => {
commonCode
};
if(condition1) {
asyncFun1().subscribe(callback);
} else {
asyncFun2().subscribe(callback);
}
Next, you see that calling subscribe is shared as well, the only difference is the object it is being called on. You might want to move that out of the condition as well (or you might want to keep it, it really depends)
const callback = (result) => {
commonCode
};
const subscribable;
if(condition1) {
subscribable = asyncFun1();
} else {
subscribable = asyncFun2();
}
subscribable.subscribe(callback);
or
const callback = (result) => {
commonCode
};
const subscribable = condition1
? asyncFun1()
: asyncFun2();
subscribable.subscribe(callback);
and then you might just inline everything again, arriving at:
(condition1 ? asyncFun1() : asyncFun2()).subscribe((result) => {
commonCode
});
Keep the variables if they make your code easier to understand (e.g. keeping subscribable, but inlining callback could make it clearer)
(condition1 ? asyncFun1 : asyncFun2)().subscribe(...)?