このページはまだ翻訳されていないため、英語で表示されます。 翻訳に参加する

takeUniqBy

The first count elements whose key is new, as a list — a null key skips the element, so one callback both selects and keys.

List<A> takeUniqBy<A, B extends Object>(int count, B? Function(A a) f, Iterable<A> iterable) List<T> Fx<T>.takeUniqBy<B extends Object>(int count, B? Function(T a) f) // chain // Strict: returns a List, runs when called. A null key skips the element, // so f both selects and keys — filter + uniqBy + take in one call.

Lecture

takeUniqBy(3, key, xs) is filter + uniqBy + take written as a single strict call. It returns a List, it runs when you call it, and it stops the moment the count is met — the elements after that are never inspected. The one twist is the callback: it returns a key, and returning null means "skip this element". That is the filter_map shape, and it is what lets one function do the work of two.

Write the chain by default. Three named steps read better than one callback doing two jobs, and the lazy chain short-circuits just as well. This operator exists for one reason, and it is worth knowing what it is.

Why it exists: the callback the compiler cannot see

A lazy stage keeps its callback in an iterator field. The AOT compiler cannot see through a field, so the closure never inlines — every element pays a real indirect call, and its body is never fused into the loop around it. Two stages, two calls per element. That is most of what separates an idiomatic FxDart chain from a hand-written loop.

takeUniqBy takes its callback as a parameter of a body small enough to inline into the caller, so the compiler inlines the closure with it. Measured over 1,000,000 log lines, AOT:

SpellingTime
filter().uniqBy().take(3)13.7 ms
takeUniqBy(3, …)11.3 ms
a hand-written loop10.2 ms

Both spellings, and both bars, are on Recent error messages, deduped — the one comparison page that publishes three bars instead of two, because the gap between two ways of writing the same pipeline is the point it makes.

So: reach for this when the pipeline is hot and a profile says these callbacks are the cost. Not before. fxdart extension — no FxTS counterpart, and no async twin: the win is inlining, which the async machinery dwarfs.

Demo 1 · The three most recent distinct errors

Demo 2 · null skips, count is a ceiling

Try it yourself

Exercise: the first three distinct users who landed on a page.

Related: uniqBy — the lazy dedup this folds in · take — the lazy truncation this folds in · uniqStrict — the other strict member of the family · Performance — where the callback floor comes from