mapNotNull · firstNotNullOf
Transform and filter in one step — the callback returns the new value, or null to skip.
Lecture
A lot of mapping is partial: parse a string that may not be a
number, look up a key that may be missing. The long-hand is a
where that runs the work to test it and a
map that runs it again to keep it, or
fxCompact(fxMap(f, xs)), which stacks two lazy stages.
mapNotNull(f, xs) does both in one stage: f
returns the new value, and a null result means
skip this element. f runs once per element, and
only when the element is pulled.
The result type B is bound to Object, so
mapNotNull(int.tryParse, xs) is an
Iterable<int>, not int? — a
null can never mean yield null.
firstNotNullOf(f, xs) is the same idea as a terminal: it
returns the first non-null result of f and stops
there, or null when every result is null (or
the input is empty). Where find
returns the element that matched,
firstNotNullOf returns the projection — no second call to
get at it.
The async twins are mapNotNullAsync and
firstNotNullOfAsync; f may return a
Future. mapNotNullAsync is built on the
parallel-safe fxMapAsync, so
concurrent(n) runs
n callbacks at once; firstNotNullOfAsync pulls one
element at a time and cancels the source at the first hit. On the chain
they are fx(xs).mapNotNull(f) and
fx(xs).firstNotNullOf(f). Dart-native addition (not part of
FxTS) — Kotlin's mapNotNull and
firstNotNullOfOrNull, Rust's filter_map.
Demo 1 · Parse what parses
Demo 2 · Async lookups that may miss
Try it yourself
Exercise: stop parsing every answer twice.