Which approach is recommended when calling multiple suspend functions inside an activity or fragment? (Some functions require the result of another operation)
lifecycleScope.launch
lambdalifecycleScope.launch
functions for every suspend functionDoes the behavior change?
Each time you call CoroutineScope.launch
, a fresh new coroutine is created and launched without blocking the current thread and returns a reference to the coroutine as a Job.
So to answer your questions:
lifecycleScope.launch {
invokeSuspend1() // This will be executed first
invokeSuspend2() // Then this will be excuted
}
The invokeSuspend1()
is executed first, and when it is done, invokeSuspend2()
is executed.
CoroutineScope.launch
functions for each suspend function will create multiple coroutines which make every suspend function independent of each other. So the order of executions is unpredictable.lifecycleScope.launch {
invokeSuspend1()
}
lifecycleScope.launch{
invokeSuspend2()
}
// What is the order of invokeSuspend1 and invokeSuspend2? You'll never know
In case functions require the result of another operation to be done, I recommend you to use a single coroutine to keep their executions sequential.