Return value only of the faster coroutine

前端 未结 2 1497
旧巷少年郎
旧巷少年郎 2021-01-03 01:18

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

相关标签:
2条回答
  • 2021-01-03 01:25

    I came up with following implementation:

    suspend fun getFaster(): Int = coroutineScope {
        select<Int> {
            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.

    0 讨论(0)
  • 2021-01-03 01:50

    You can use select to write your own amb operator. Something like that:

    suspend fun <T> amb(vararg jobs: Deferred<T>): T = select {
        fun cancelAll() = jobs.forEach { it.cancel() }
    
        for (deferred in jobs) {
            deferred.onAwait {
                cancelAll()
                it
            }
        }
    }
    

    You can read more about select expression here

    0 讨论(0)
提交回复
热议问题