André Martins
04/06/2022, 4:07 PMsuspend fun getApples(): List<Apple> = ...
suspend fun getPotatos(): List<Potato> = ...
fun work(): ReceiveChannel<SomeResult> = GlobalScope.produce {
try {
val (apples, potatos) = coroutineScope {
val getApples = async {
val (resp, time) = measureTimedValue {
getApples()
}
<http://logger.info|logger.info> { time.inWholeMilliseconds }
resp
}
val getPotatos = async {
val (resp, time) = measureTimedValue {
getPotatos()
}
<http://logger.info|logger.info> { time.inWholeMilliseconds }
resp
}
getApples.await() to getPotatos.await()
}
send(doSomething(apples, potatos))...
} catch(ex: Exception) {
handle...
}
}
Joffrey
04/06/2022, 4:11 PMgetApples()
and getPotatoes()
switching context? Are they using a single-threaded dispatcher?
Also, where are you returning the value of the coroutineScope
as a pair? It's not in the code you provided (there are no await()
anywhere there)André Martins
04/06/2022, 4:12 PMwithContext(<http://Dispatchers.IO|Dispatchers.IO>)
since its a network requestAndré Martins
04/06/2022, 4:13 PMJoffrey
04/07/2022, 8:39 AMGlobalScope
(which doesn't have a dispatcher), produce
should be defaulting to the multi-threaded Dispatchers.Default
. If you can reproduce the problem in isolation (with nothing else eating the threads from the default pool) then I don't know what the cause could be. Do you have a minimal reproducible example?Joffrey
04/07/2022, 8:41 AMsuspend fun work(): SomeResult {
try {
val (apples, potatos) = coroutineScope {
val getApples = async {
val (resp, time) = measureTimedValue {
getApples()
}
<http://logger.info|logger.info> { time.inWholeMilliseconds }
resp
}
val getPotatos = async {
val (resp, time) = measureTimedValue {
getPotatos()
}
<http://logger.info|logger.info> { time.inWholeMilliseconds }
resp
}
getApples.await() to getPotatos.await()
}
return doSomething(apples, potatos)
} catch(ex: Exception) { // <-- this could catch CancellationException, and it's pretty bad. Try to narrow it down
handle...
}
}
Also, as mentioned, cancellation will be prevented by your catch-all block - please try to find a narrower exception to catch (what is the purpose of this catch block in the first place?).