在 Kotlin 中,使用协程,假设我有一项工作,它通过单击按钮开始,并且在调用 Activity 的 onStop
之前不应该结束。
看起来像这样的东西:
button.setOnClickListener {
CoroutineScope(...).launch{
print("Button clicked")
// How to wait for "onStop()" ?
print("Activity stopped")
}
}
以上场景只是一个一般需要合并的例子
SDK 中以函数调用形式出现的异步事件 (onStop()
)。
应该怎么做?谢谢:]
最佳答案
我会为一个按钮创建一个特殊的 channel ,而不是从 onStop(0)
向它发送一些东西,然后在你的代码中等待它:
val onStopChannel = Channel<Int>()
fun onStop() {
onStopChannel.offer(0)
}
button.setOnClickListener {
CoroutineScope(...).launch{
print("Button clicked")
onStopChannel.receive()
print("Activity stopped")
}
}
任何其他 observable 也可以工作。
关于android - 我如何等待 Kotlin 协程中的其他事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870773/