I have a suspend kotlin function which should get the first value from a flow and return it. However it stucks on ch.send(st)
private suspend fun readSensorTemperature(): Double {
val ch = Channel<Double>()
val job = coroutineScope {
launch {
myFlow.collect { st ->
ch.send(st)
}
}
}
val res = ch.receive()
job.cancel()
return res
}
Why my code does not work?
Do you really need to do this? A simpler way to get the first value from a flow is with
myFlow.first()
.The reason your current code is suspending indefinitely is that the call to
coroutineScope
will suspend until all of its child coroutines have completed.Because you call
collect
inside thecoroutineScope
, thecoroutineScope
cannot complete until the flow collection has completed. That means your code will never reach the calls toreceive
andcancel
which would allow the flow collection to proceed and then be terminated.A solution would be to move the
receive
andcancel
calls inside thecoroutineScope
.