How can I run multiple coroutines in parallel and return only the value of the one that finishes first?
Real-life scenario, I have two data sources - Database
I came up with following implementation:
suspend fun getFaster(): Int = coroutineScope {
select {
async { getFromServer() }.onAwait { it }
async { getFromDB() }.onAwait { it }
}.also {
coroutineContext.cancelChildren()
}
}
The coroutineScope acts as a parent to all async calls performed within. After the select finishes we can just cancel the rest.