我如何使用当前的 CoroutineScope 来实现挂起函数中的 `CoroutineScope.async`?

问题描述 投票:0回答:0

如果我想使用其他挂起功能的当前

CoroutineScope

我怎样才能找回它?

下面的代码是我试过的。

fun main() = CoroutineScope(Dispatchers.IO).launch {
    val result = getTitleAndLabel() // suspend function
    // doSomthing with result
}
#Case1
// Ambiguous coroutineContext due to CoroutineScope receiver of suspend function
suspend fun CoroutineScope.getTitleAndLabel() {
    val titleDeferred = async { getTitle() }
    val labelDeferred = async { getLabel() }
    val (title, label) = listOf(titleDeferred, labelDeferred).awaitAll()
    return Pair(title, label)
}
#Case2
// It makes another CoroutineScope
suspend fun getTitleAndLabel() = coroutineScope {
    val titleDeferred = async { getTitle() }
    val labelDeferred = async { getLabel() }
    val (title, label) = listOf(titleDeferred, labelDeferred).awaitAll()
    return Pair(title, label)
}
#Case3
// No need to do ContextSwitching
suspend fun getTitleAndLabel() = withContext(Dispatchers.IO) {
    val titleDeferred = async { getTitle() }
    val labelDeferred = async { getLabel() }
    val (title, label) = listOf(titleDeferred, labelDeferred).awaitAll()
    return Pair(title, label)
}
#Case4
// Passing CoroutineScope as an argument?
suspend fun getTitleAndLabel(coroutineScope: CoroutineScope) {
    val titleDeferred = coroutineScope.async { getTitle() }
    val labelDeferred = coroutineScope.async { getLabel() }
    val (title, label) = listOf(titleDeferred, labelDeferred).awaitAll()
    return Pair(title, label)
}

#Case1, #Case2, #Case3, #Case4

kotlin kotlin-coroutines coroutine
© www.soinside.com 2019 - 2024. All rights reserved.