kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

Integrate with KotlinX Immutable Collections, add `Flow.toMap`

Open Laxystem opened this issue 1 year ago • 4 comments
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.

Laxystem avatar Nov 14 '24 11:11 Laxystem