kotlin coroutines - 阻塞线程直到超时或收到消息计数
kotlin coroutines -block thread until timeout or message count received
对于 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 协程最eloquent 的方法是什么?
在对 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
}
对于 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 协程最eloquent 的方法是什么?
在对 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
}