associateWith

inline suspend fun <K, V> Flow<K>.associateWith(crossinline valueSelector: suspend (K) -> V): Map<K, V>(source)

Collects this Flow into a Map with the keys being the Flow elements and the corresponding values being obtained from them using valueSelector.

If the same element is emitted more than once, the last value returned by valueSelector gets added to the map.

The entry iteration order of the resulting Map is the order of the elements in the original Flow.

The operation is terminal.

val words = flowOf("a", "abc", "ab", "def", "abcd")
val withLength = words.associateWith { it.length }
println(withLength.keys) // [a, abc, ab, def, abcd]
println(withLength.values) // [1, 3, 2, 3, 4]