运行 withContext 与 suspendCoroutine 的协程函数

Running coroutines function with withContext vs suspendCoroutine

我希望你能详细说明调用这 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并不是真正的挂起函数