I would like to suspend a kotlin coroutine until a method is called from outside, just like the old Java object.wait() and object.notify() methods. How do I do that?

这里: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 can be used for this (though they are more general):

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.

So create

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中的增广赋值语句中的难以理解的错误

如何在Spring Boot中注册新的集合工厂

用Quarkus和Reactor重写异步过滤器中的数据流

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

当 func 重载时,kotlin 如何确定调用哪个 func?

如何限制 Kotlin 中的枚举?

Jetpack BottomNavigation - java.lang.IllegalStateException:Already attached to lifecycleOwner

如何使用 Kotlin KClass 属性 simpleName 生成空值

Saripaar formvalidation 在 kotlin 中第二次不起作用

如何为你的 Flutter 元素添加 Kotlin 支持?

Kotlin 中的 Java Scanner 相当于什么?

IntentService (kotlin) 的默认构造函数

使用 Paging 3 时保存并保留 LazyColumn 滚动位置

Kotlin:子构造函数如何使用其父构造函数的辅助构造函数?

如何在Kotlin中使用ViewModelProviders

具有泛型param的Kotlin抽象类和使用类型param的方法

Kotlin数据类打包

为什么 Kotlin 会收到这样的 UndeclaredThrowableException 而不是 ParseException?

如何判断数据是否插入到房间数据库中