gpt4 book ai didi

kotlin - 如何在通知之前暂停Kotlin协程

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

我想暂停一个kotlin协程,直到从外部调用一个方法为止,就像旧的Java object.wait()和object.notify()方法一样。我怎么做?

在这里:Correctly implementing wait and notify in Kotlin是如何使用Kotlin线程(阻塞)实现此目标的答案。在这里:Suspend coroutine until condition is true是如何使用CompleteableDeferreds做到这一点的答案,但我不想每次都必须创建一个新的CompleteableDeferred实例。

我目前正在这样做:

    var nextIndex = 0

fun handleNext(): Boolean {
if (nextIndex < apps.size) {
//Do the actual work on apps[nextIndex]
nextIndex++
}
//only execute again if nextIndex is a valid index
return nextIndex < apps.size
}

handleNext()

// The returned function will be called multiple times, which I would like to replace with something like notify()
return ::handleNext

来自: https://gitlab.com/SuperFreezZ/SuperFreezZ/blob/master/src/superfreeze/tool/android/backend/Freezer.kt#L69

最佳答案

Channels可以用于此目的(尽管它们更通用):

When capacity is 0 – it creates RendezvousChannel. This channel does not have any buffer at all. An element is transferred from sender to receiver only when send and receive invocations meet in time (rendezvous), so send suspends until another coroutine invokes receive and receive suspends until another coroutine invokes send.



所以创造
val channel = Channel<Unit>(0)

并使用 channel.receive() 表示 object.wait(),并使用 channel.offer(Unit) 表示 object.notify()(如果要等到其他协程 send,则使用 receive)。

对于 notifyAll,可以改为使用 BroadcastChannel

您当然可以轻松地封装它:
inline class Waiter(private val channel: Channel<Unit> = Channel<Unit>(0)) {

suspend fun doWait() { channel.receive() }
fun doNotify() { channel.offer(Unit) }
}

关于kotlin - 如何在通知之前暂停Kotlin协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55421710/

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