I have my code below
interface Listener {
fun onGetData(data: Int)
fun onClose()
}
class MyEmitter {
var listener: Listener? = null
fun sendData(data: Int) = listener?.onGetData(data)
fun close() = listener?.onClose()
}
fun handleInput(myEmitter: MyEmitter) = channelFlow {
myEmitter.listener = object:Listener {
override fun onGetData(data: Int) { trySend(data) }
override fun onClose() { close() }
}
}
fun main(): Unit = runBlocking {
val myEmitter = MyEmitter()
handleInput(myEmitter).collect {
println(it)
}
myEmitter.sendData(1)
myEmitter.sendData(2)
myEmitter.close()
}
Whenever I send the data e.g. myEmitter.sendData(1)
, it does get into trySend(data)
, but the result is closed
.
Why is it closed? How can I keep it open?
To get this working, I did 3 things
awaitClose
to ensure the flow is not terminatedlaunch
, so that it is not blocking themain()
function flowdelay
beforemyEmitter.sendData(1)
, so that to ensure thelaunch
get triggered first before doing the externalsendData
.Full changed code as below
The 3rd step is a little hack I think.