kotlin coroutines -block线程,直到超时或收到消息计数

问题描述 投票:0回答:1

使用Kotlin,我会阻塞一个线程,直到从回调MessageBroker收到n条消息(或发生超时);

例如 - 有点像;

fun receivedMessages(numberOfMessages: Int, timeout: Long): List<Message> {
receivedMessages: ArrayList<Message>

//subscribe to a queue and get a callback for EACH message on the queue e.g.

//listen until the 'numberOfMessages' have been reveived OR the timeout is reached. e.g.

async - block
{
    messageQueue.setMessageListener
    (message -> {
    receivedMessages.add(message)
    if (receivedMessages.size > numberOfMessages) //break out of the routine
})

    //else - if timeout is reached - break the routine.
}.withTimeout(timeout)


return receviedMessages

}

用kotlin协同程序做这个最有说服力的方法是什么?

kotlin coroutine completable-future
1个回答
1
投票

经过对Kotlin协同程序的大量研究后,我决定简单地使用CountdownLatch并将其倒计时,直到收到messageCount为止;例如;

private fun listenForMessages(consumer: MessageConsumer,messageCount: Int, 
                              timeout: Long): List {
    val messages = mutableListOf<T>()
    val outerLatch = CountDownLatch(messageCount)
    consumer.setMessageListener({ it ->
        //do something
        outerLatch.countDown()
    }
})
outerLatch.await(timeout)
return messages
}
© www.soinside.com 2019 - 2024. All rights reserved.