如果我想使用其他挂起功能的当前
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