kotlinx.coroutines
kotlinx.coroutines copied to clipboard
Integrate with KotlinX Immutable Collections, add `Flow.toMap`
trafficstars
This could be done fairly easily:
suspend fun <T> Flow<T>.toPersistentList() = emptyPersistentHashList<T>().mutate { toList(it) }
public suspend fun <K, V, M : MutableMap<in K, in V>> Flow<Pair<K, V>>.toMap(destination: M): M {
collect { (key, value) ->
destination[key] = value
}
return destination
}
suspend fun <K, V> Flow<Pair<K, V>>.toPersistentHashMap() = emptyPersistentHashMap<Pair<K, V>>().mutate { toMap(it) }
I used mutate instead of toXxx(mutableXxxOf()).toPersistentXxx() as the mutate function uses builders, that KotlinX Immutable Collections can optimize.
A nice addition to complement the toMap that is necessary for this suggestion would be a Map.asFlow.