kotlin协程 – 阻塞线程,直到收到超时或消息计数

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

例如 – 类似的东西;

fun receivedMessages(numberOfMessages: Int, timeout: Long): List { receivedMessages: ArrayList //subscribe to a queue and get a callback for EACH message on the queue eg //listen until the 'numberOfMessages' have been reveived OR the timeout is reached. eg 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的协程的大量研究,我决定简单地使用CountdownLatch ,并倒计时直到收到messageCount; 例如;

 private fun listenForMessages(consumer: MessageConsumer,messageCount: Int, timeout: Long): List { val messages = mutableListOf() val outerLatch = CountDownLatch(messageCount) consumer.setMessageListener({ it -> //do something outerLatch.countDown() } }) outerLatch.await(timeout) return messages } 
Interesting Posts