DRY (Don't Repeat Yourself)
Suppose I have this code used a lot in my app:
observable$.pipe(
tap(value => console.log(value)),
map(value => value * 5),
... more repeated stuff
)
Suppose that the value 5 is different in some parts of the code but everything else is identical. Can I somehow functionalise / do something to this to make it reusable to avoid copy paste issues?
Could I do something like this?
observable$.pipe(
getReusedOperators(7), // this would pipe to all above operators using 7 instead of 5
tap((value) => console.log('im not reused and my value is', value)),
....
)
What is the best approach here? Sorry, my question not great but hopefully you get the idea.
The thing to remember with pipeable operators is that they are just functions that take an observable and return an observable, so you can easily create reusable combinations of operators like this:
function getReusedOperators(factor) {
return source => source.pipe(
tap(value => console.log(value)),
map(value => value * factor),
);
}
And for situations in which your reusable combination is not parameterized, you can just compose using the static pipe function. See my Combining Operators article for some examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With