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

时间:2018-01-17 17:06:35

标签: kotlin coroutine completable-future

使用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协同程序执行此操作的最有说服力的方法是什么?

1 个答案:

答案 0 :(得分: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
}