Samoxive
09/03/2018, 11:28 AMfun blockingFunction(): Int {
val foo = blockingFoo();
val bar = blockingBar(bar);
val baz = blockingBaz(bar);
}
normally, you would run this in an executor, get the integer via a future object or somethingMartin Devillers
09/03/2018, 11:33 AMSamoxive
09/03/2018, 11:38 AMMartin Devillers
09/03/2018, 11:58 AMasync { blockingFunction() }.await()
, it’ll work and it’ll do the computing asynchronously, but it’ll starve the coroutine context of a thread while it’s blocked. The intermediate solution is something like newSingleThreadContext().use { async(it) { blockingFunction() }}
, which will work pretty much the same as your code currently does, but it can act as a seam for new code calling this one with coroutines.Samoxive
09/03/2018, 12:01 PMasync { block() }.await()
method, but since you are saying that it would starve the global coroutine thread pool, i fail to see how coroutines help hereMartin Devillers
09/03/2018, 12:04 PMExecutorService.asCoroutineDispatcher
to obtain a context from your current cached thread pool, and do an async
with that contextSamoxive
09/03/2018, 12:08 PMMartin Devillers
09/03/2018, 12:18 PMexecutor.execute {
val result = blockingFunction()
doOnUiThread {
// Something with result
}
}
With coroutines you’ll be able to combine it with other work in an imperative manner
launch(UI) {
val result = async(NetworkContext) { blockingFunction }
// Something with result
}
Samoxive
09/03/2018, 12:22 PM