Reputation: 483
I need to return a value within an asynchronous callback. This value is acquired asynchronously as a websocket acknowledgement, and I can't find a way to block that callback's execution until the value is retrieved... I have tried all combinations of coroutines to no avail.
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
}
Upvotes: 2
Views: 799
Reputation: 93639
Presumably the function is called from a thread where it's OK to block. You can use a CountDownLatch to wait for it.
override fun someAsyncCallback() : String
{
var myAsyncValue = ""
val latch = CountDownLatch(1)
socket.emit(event = "someEvent", callback = { result ->
myAsyncValue = result
latch.countDown()
})
latch.await()
return myAsyncValue
}
You can also pass a timeout to the latch.await()
method so this doesn't block indefinitely.
Upvotes: 2