Esta página ainda não foi traduzida, por isso é exibida em inglês. Ajude a traduzir

mapNotNull · firstNotNullOf

Transform and filter in one step — the callback returns the new value, or null to skip.

Iterable<B> mapNotNull<A, B extends Object>(B? Function(A a) f, Iterable<A> iterable) FxAsyncIterable<B> mapNotNullAsync<A, B extends Object>(FutureOr<B?> Function(A a) f, FxAsyncIterable<A> iterable) B? firstNotNullOf<A, B extends Object>(B? Function(A a) f, Iterable<A> iterable) Future<B?> firstNotNullOfAsync<A, B extends Object>(FutureOr<B?> Function(A a) f, FxAsyncIterable<A> iterable) Fx<R> Fx<T>.mapNotNull<R extends Object>(R? Function(T a) f) // chain (sync) R? Fx<T>.firstNotNullOf<R extends Object>(R? Function(T a) f) // chain (sync) FxAsync<R> FxAsync<T>.mapNotNull<R extends Object>(FutureOr<R?> Function(T a) f) // chain (async) Future<R?> FxAsync<T>.firstNotNullOf<R extends Object>(FutureOr<R?> Function(T a) f) // chain (async)

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.

Related: map — when every element has a result · where — keep elements, unchanged · nonNulls — drop the nulls already there · find — the first matching element, not its projection