Antimonit
07/11/2019, 11:30 AMasync
coroutines that both return the same type. I want to return only the value of the coroutine that finishes first and discard the value of the slower one. I have found that select
takes care of selecting and returning value the faster coroutine but the other one is not cancelled and coroutineScope waits until the other one returns too. What would be the best approach?suspend fun getFaster(): Int = coroutineScope {
select<Int> {
async { getFromServer() }.onAwait { it }
async { getFromDB() }.onAwait { it }
}.also {
coroutineContext.cancelChildren()
}
}
Zach Klippenstein (he/him) [MOD]
07/11/2019, 5:34 PMcoroutineScope
that canceled its children after instead of joining on them, because this seems like a pretty common use case.Jag
07/13/2019, 2:36 AMfun getFromServer(): Flow<Int> { ... }
fun getFromDB(): Flow<Int> { ... }
suspend fun getFaster(): Int = flowOf(getFromServer(), getFromDB()).flattenMerge(2).first()
under the hood I suspect it’s not as efficient as the select approach, but I suppose that’s acceptable given network and db latenciesZach Klippenstein (he/him) [MOD]
07/13/2019, 10:35 PM