考虑一个报告其操作进度的异步 API:
suspend fun operationWithIO(input: String, progressUpdate: (String) -> Unit): String {
withContext(Dispatchers.IO) {
// ...
}
}
是否可以实现对 progressUpdate
的调用,以便在调用者的调度程序上处理回调?或者是否有更好的方法将状态更新传递回调用者?
最佳答案
您应该在 channel 上发送进度更新。这将允许调用者使用它想要的任何调度程序来监听 channel 。
suspend fun operationWithIO(input: String, progressChannel: Channel<String>): String {
withContext(Dispatchers.IO) {
// ...
progressChannel.send("Done!")
progressChannel.close()
}
}
调用者可以通过执行以下操作来使用它:
val progressChannel = Channel<String>()
someScope.launch {
operationWithIO(input, progressChannel)
}
// Remember the call to progressChannel.close(), so that this iteration stops.
for (progressUpdate in progressChannel) {
println(progressUpdate)
}
关于kotlin - 从协程获取状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54580903/