Michael Kotlikov
02/18/2018, 11:04 PMsuspend fun <T> asyncResult(execute: () -> T): T {
data class AsyncResponse<T>(val result: T?, val exception: Exception?)
val responseChannel = Channel<AsyncResponse<T>>()
val asyncResponse: AsyncResponse<T>?
CompletableFuture.runAsync {
try{
val executionResult = execute()
launch(NoopContinuation.context) {
responseChannel.send(AsyncResponse(
result = executionResult,
exception = null
))
}
} catch(exception: Exception) {
launch(NoopContinuation.context) {
responseChannel.send(AsyncResponse(
result = null,
exception = exception
))
}
}
}
asyncResponse = responseChannel.receive()
if (asyncResponse.exception != null) {
throw asyncResponse.exception
}
return asyncResponse.result!!
}