希望您能详细说明调用这 3 个函数时的区别:
lifecycleScope.launch(Dispatchers.IO) {
var res = addTwoNumbers1(2,3)
}
lifecycleScope.launch {
withContext(Dispatchers.IO) {
var res = addTwoNumbers1(2, 3)
}
}
lifecycleScope.launch {
var res = addTwoNumbers2(2,3)
}
功能:
suspend fun addTwoNumbers1(num1: Int, num2: Int): Int = suspendCoroutine { cont ->
val res = num1+num2
cont.resume(res)
}
suspend fun addTwoNumbers2(num1: Int, num2: Int) = withContext(Dispatchers.IO) {
val res = num1+num2
return@withContext res
}
最佳答案
第一个版本使用 Dispatcher.IO
启动协程,这意味着内部的任何代码都将在后台线程上执行,除非您更改它
lifecycleScope.launch(Dispatchers.IO) {
var res = addTwoNumbers1(2,3) // This call executes on background thread (IO pool)
}
第二个版本使用 Dispatchers.Main.immediate
启动协程(UI 线程,这对于 lifecycleScope
是隐式的)
lifecycleScope.launch { // Starts on UI thread
withContext(Dispatchers.IO) { // Here thread is changed to background (IO pool)
var res = addTwoNumbers1(2, 3)
}
}
第三个在 UI
线程上启动一个新的协程,然后调用一个挂起函数(实际上并不挂起),该函数将 Dispatcher
更改为 IO
lifecycleScope.launch { // Starts on UI thread
var res = addTwoNumbers2(2,3) // This function changes the dispatcher to IO
}
对于您的挂起函数,addTwoNumbers1
是唯一具有挂起功能的函数,因为它调用 suspendCoroutine。
addTwoNumbers2
并不是真正的挂起函数
关于android - 使用 withContext 与 suspendCoroutine 运行协程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68526681/