我希望你能在调用这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
}发布于 2021-07-26 17:56:56
第一个版本使用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并不是真正的挂起函数
https://stackoverflow.com/questions/68526681
复制相似问题