So i've been using Java 8 Completable Futures for ...
# coroutines
m
So i've been using Java 8 Completable Futures for running CPU heavy and blocking operations instead of coroutines to avoid starving the CPU time of coroutines scheduled on the same thread:
Copy code
suspend 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!!
}