Kush Patel
10/07/2020, 12:40 AMval workers = ArrayList<Future<*>>(10)
try {
for (i in 1..10) {
val task = getTask() ?: break
workers += taskExecutor.submit {
workerLoop(task) // some computation
}
}
} catch (t: Throwable) {
// log error
}
workers.forEach {
try {
it.get()
} catch (t: Throwable) {
// log error
}
}
Proposed coroutine worker
val workers = ArrayList<Deferred<*>>(10)
try {
for (i in 1..10) {
val task = getTask() ?: break
workers += taskExecutor.async {
workerLoop(task) // some computation
}
}
} catch (t: Throwable) {
// Log error
}
runBlocking {
workers.forEach {
try {
it.await()
} catch (t: Throwable) {
// Log error
}
}
}
Is this the right way to switch from threads to coroutines?gildor
10/07/2020, 1:27 AMtry { it.await() }
I would return some result from Deferred, so try/catch workerLoop(task) insteadtaskExecutor
partKush Patel
10/07/2020, 2:59 AMtaskExexutor
is a cached thread pool. So Executors.newCachedThreadPool {}
taskExecutor
as a coroutine dispatcher in a separate coroutine scopegildor
10/07/2020, 4:54 AMsuspend fun doSomethingInParallel(
dispatcher: CoroutineDispatcher = taskExecutor
): List<Result<Something>> = withContext(dispatcher) {
(1..10).map { i ->
async {
// or any other way to encode failed/successful tasks
runCatching {
workerLoop(getTask())
}
}
}.awaitAll()
}