gpt4 book ai didi

kotlin - 从协程获取状态更新

转载 作者:行者123 更新时间:2023-12-02 12:47:22 24 4
gpt4 key购买 nike

考虑一个异步API,该API报告其操作进度:

suspend fun operationWithIO(input: String, progressUpdate: (String) -> Unit): String {
withContext(Dispatchers.IO) {
// ...
}
}

是否可以实现对 progressUpdate的调用,以便在调用者的调度程序上处理回调?还是有更好的方法将状态更新传递回 call 者?

最佳答案

您应该在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com