From Kotlin 1.4, suspend conversion on callable references is supported π Release note doesn't say much about this feature but it's really helpful when you use Flow#combine()
.
Let's pretend you want to combine two flows and use them in collect()
. Before Kotlin 1.4, you may write code like this:
suspend fun before4_1() {
combine(
flowA, flowB
) { a, b ->
a to b
}.collect {
val a = it.first
val b = it.second
println("$a and $b")
}
}
val flowA = flowOf(1, 2)
val flowB = flowOf(3, 4)
This code is kind of redundant and doesn't look great (too much a
s and b
s! π©)
From Kotlin 1.4, you can simplify the above code.
suspend fun from1_4() {
combine(
flowA, flowB, ::Pair
).collect { (a: Int, b: Int) ->
println("$a and $b")
}
}
val flowA = flowOf(1, 2)
val flowB = flowOf(3, 4)
Before Kotlin 1.4, this code causes compile error because the type of the 3rd parameter of combine()
is suspend function. Pair
class constructor is not a suspend function so compile error will occur. From Kotlin 1.4, this 3rd parameter lambda will be converted to suspend function
automatically and work fine.
Bounus: I use destructuring declarations for the parameter of collect()
.
).collect { (a: Int, b: Int) ->
We can name values of pair.first
and pair.second
here. Type definition can be omitted but ()
is necessary.
Top comments (0)