lastOrNull
Returns the final element of an iterable, or null when it's empty.
Lecture
lastOrNull walks the whole iterable and hands back whatever
it saw most recently — null if it never saw anything.
lastOrNull is the Dart-idiomatic name (it mirrors
Iterable.lastOrNull); fxdart also accepts the FxTS spelling
last — they're the same operator. Unlike
head, there's no shortcut: since a lazy iterable doesn't
know where it ends without being asked, lastOrNull has to
consume every element, so it's O(n) even though the pipeline
upstream may be lazily built.
Watch out on the sync chain: Fx extends
Iterable, so fx(iterable).lastOrNull resolves to
Dart's own inherited Iterable.lastOrNull getter
(no parens) — which is null-safe and returns null on
an empty iterable. The trap is the neighboring .last getter
(no "OrNull"): fx(<int>[]).last throws
StateError instead of returning null. Reach for
.lastOrNull, or the top-level lastOrNull(iterable)
function. On the async chain, .lastOrNull() is a
method — with parens.
Demo 1 · Basics, and the chain getter trap
Demo 2 · Async, where the chain form IS null-safe
FxAsync defines its own .lastOrNull() method, so on the async chain the getter trap above doesn't apply:
Try it yourself
Exercise: use lastOrNull so this prints the final log line, or 'no logs yet' when there are none.