我需要在异步回调中返回一个值。此值是作为Websocket确认异步获取的,在找到该值之前,我无法找到一种方法来阻止该回调的执行...我尝试了协程的所有组合,但无济于事。
override fun someAsyncCallback() : String
{
var myAsyncValue = ""
socket.emit(event = "someEvent", callback = { result ->
//This is an asynchronous callback
myAsyncValue = result
})
//Insert way to wait for the async value to be set
return myAsyncValue
}
答案 0 :(得分:1)
大概是从可以阻塞的线程中调用该函数。您可以使用CountDownLatch等待它。
override fun someAsyncCallback() : String
{
var myAsyncValue = ""
val latch = CountDownLatch(1)
socket.emit(event = "someEvent", callback = { result ->
myAsyncValue = result
latch.countDown()
})
latch.await()
return myAsyncValue
}
您还可以将超时传递给latch.await()
方法,这样就不会无限期地阻塞。