observable.pipe(
tap((booleanValue) => {
if (booleanValue) {
doSomething();
}
}),
)
Is there a best practice or a better way to do this?
I don’t want to filter
because the data still needs to stream, only the tap
action is conditional.
2
Your second best alternative after writing what you proposed it to implement a custom rxjs operator yourself.
For example
function conditionalTap(conditionFn, tapFn) {
return (source$) => source$.pipe(
tap(value => {
if (conditionFn(value)) {
tapFn(value);
}
})
);
}
source$
.pipe(
map(x => x * 2),
conditionalTap(
value => value > 5, // Condition function
value => console.log(`Value greater than 5: ${value}`) // Tap function
)
)
.subscribe(value => console.log(`Output: ${value}`));