在Activity/Fragment中调用多个挂起函数

Eto*_*eno 8 android kotlin android-architecture-components kotlin-coroutines

在活动或片段内调用多个挂起函数时建议使用哪种方法?(有些函数需要另一个操作的结果)

  1. 调用一个lifecycleScope.launchlambda内的每个函数
  2. lifecycleScope.launch每个挂起函数使用多个函数

行为会改变吗?

Sơn*_*han 11

每次调用时CoroutineScope.launch,都会创建并启动一个全新的协程,而不会阻塞当前线程,并返回对协程的引用作为作业。

所以回答你的问题:

  1. 这些挂起函数将在单个协程中执行。这意味着什么?这意味着它们的执行顺序将是连续的。
lifecycleScope.launch {
    invokeSuspend1() // This will be executed first
    invokeSuspend2() // Then this will be excuted
}
Run Code Online (Sandbox Code Playgroud)

首先执行invokeSuspend1(),完成后再invokeSuspend2()执行。

  1. 对每个挂起函数使用多个CoroutineScope.launch函数将创建多个协程,这使得每个挂起函数彼此独立。所以执行的顺序是不可预测的。
lifecycleScope.launch {
    invokeSuspend1()
}

lifecycleScope.launch{
    invokeSuspend2()
}

// What is the order of invokeSuspend1 and invokeSuspend2? You'll never know
Run Code Online (Sandbox Code Playgroud)

如果函数需要完成另一个操作的结果,我建议您使用单个协程来保持它们的执行顺序。