We’re getting a flow of rows from the database (th...
# coroutines
f
We’re getting a flow of rows from the database (through r2dbc) like this:
Copy code
db.execute { ... }.asType<Foo>().fetch().flow()
Now we want to return a Map. Two ways of doing that are:
Copy code
db.execute { ... }.asType<Foo>().fetch().flow().fold(mapOf()) { acc, it -> acc + (transform(it.bar) to it.baz) }
or:
Copy code
db.execute { ... }.asType<Foo>().fetch().flow().map(transform(it.bar) to it.baz).toList().toMap()
Which is better and why?
j
I prefer the last one, more readable
f
is there a performance difference? e.g. due to
toList
?
e
the first one is creating a new Map with every item in the flow, so the second one should be preferable from a performance standpoint too
f
thank you, @Javier and @ephemient!
e
if you want to define your own extension, you could
Copy code
suspend fun <T, K, V> Flow<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V> = buildMap {
    collect {
        val (key, value) = transform(it)
        set(key, value)
    }
}

db.execute { ... }.asType<Foo>().fetch().flow().associate { transform(it.bar) to it.baz }
f
that would be more readable if we use it often, but would it also be faster?
e
you can benchmark it yourself... but expect yes, it won't create an intermediate list
f
thanks a lot!