The answer is, NO, collect is not only internal kotlinx.coroutines API. The error message is misleading.
As per @ir42’s comment, add import kotlinx.coroutines.flow.collect solve the problem.
Additional info, why I didn’t pick collectLatest as the answer
collect and collectLatest is different.
Using this example
fun simple(): Flow<Int> = flow { // flow builder
for (i in 1..3) {
delay(100) // pretend we are doing something useful here
emit(i) // emit next value
}
}
fun main() = runBlocking<Unit> {
// Launch a concurrent coroutine to check if the main thread is blocked
launch {
for (k in 1..3) {
println("I'm not blocked $k")
delay(100)
}
}
// Collect the flow
simple().collect { value -> println(value) }
}
Collect will produce
I'm not blocked 1
1
I'm not blocked 2
2
I'm not blocked 3
3
as per https://kotlinlang.org/docs/reference/coroutines/flow.html
But collectLatest
fun simple(): Flow<Int> = flow { // flow builder
for (i in 1..3) {
delay(100) // pretend we are doing something useful here
emit(i) // emit next value
}
}
fun main() = runBlocking<Unit> {
// Launch a concurrent coroutine to check if the main thread is blocked
launch {
for (k in 1..3) {
println("I'm not blocked $k")
delay(100)
}
}
// Collect the flow
simple().collectLatest { value -> println(value) }
}
will produce
I'm not blocked 1
I'm not blocked 2
1
I'm not blocked 3
2