kotlin - 从协程获取状态更新

标签 kotlin callback kotlinx.coroutines

考虑一个报告其操作进度的异步 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/

相关文章:

android - 如何组合不同的testInstrumentationRunner

spring - Autowiring 参数作为bean声明参数

javascript - 为什么回调函数中的react state(array)为空?为什么它不使用外部范围的更新值?

kotlin - 使用 Kotlin Channel 是什么意思?

android - 使用MVVM在RecyclerView的网格和线性之间切换的更好方法是什么?

javascript - 等待一个函数返回一个值,然后再继续执行其他函数的其余命令

javascript - 从回调中更新 javascript 父变量

kotlin - 如何传播来自作业的异常?

android - 当被另一个对象(如 TextWatcher)封装时,参与者或 channel 是否需要被管理(关闭/终止)?

kotlin - 在 Kotlin 中按多个字段对集合进行排序