Eto*_*eno 8 android kotlin android-architecture-components kotlin-coroutines
在活动或片段内调用多个挂起函数时建议使用哪种方法?(有些函数需要另一个操作的结果)
lifecycleScope.launchlambda内的每个函数lifecycleScope.launch每个挂起函数使用多个函数行为会改变吗?
Sơn*_*han 11
每次调用时CoroutineScope.launch,都会创建并启动一个全新的协程,而不会阻塞当前线程,并返回对协程的引用作为作业。
所以回答你的问题:
lifecycleScope.launch {
invokeSuspend1() // This will be executed first
invokeSuspend2() // Then this will be excuted
}
Run Code Online (Sandbox Code Playgroud)
首先执行invokeSuspend1(),完成后再invokeSuspend2()执行。
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)
如果函数需要完成另一个操作的结果,我建议您使用单个协程来保持它们的执行顺序。
| 归档时间: |
|
| 查看次数: |
2433 次 |
| 最近记录: |