Conditional flatMap’ing

(Assumed audience: folks with a working knowledge of reactive operators and type erasure. Familiarity with Combine isn’t needed to read along.)

Let’s warm up1 with a shorter post, shall we?

Shai showed me how to rewrite awkward “conditional flatMaps”—or relatedly, “conditional map and switchToLatest” sequences.

Less abstractly, when we find ourselves checking a condition on upstream’s values and then flatMaping on matches.

I’ve ordered the comments below to read more easily.

If we squint at the chain long enough—feel free to do so, if you don’t want spoilers—, a reworking shakes out.

And that’s what Shai taught me.

The else clause is a reactive no-op we can replicate by filtering out false conditional checks entirely.

*

A small trick to add to the tool belt.

If you find yourself Emptying out a sequence, it might be better to filter in on the conditions you’re considering, letting downstream lean on the checked precondition.

This is the reactive parallel to guarding out early.


Footnotes

  1. It’s been some time since I’ve written here—trying not to beat myself up over the hiatus because well, a lot of Life has happened since the last entry and well, gestures widely at the macro state of affairs