Calling multiple suspend functions in Activity/Fragment

Viewed 1334

Which approach is recommended when calling multiple suspend functions inside an activity or fragment? (Some functions require the result of another operation)

  1. Call every function inside one lifecycleScope.launch lambda
  2. Use multiple lifecycleScope.launch functions for every suspend function

Does the behavior change?

2 Answers

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:

  1. These suspend functions will be executed in a single coroutine. What does that mean? It means their order of execution will be sequential.
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.

  1. Use multiple 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.

It depends what those functions are trying to. If they are dependent of the result of another suspend function, launch all of them within the same launch job.

If some of them can be run asynchronously, wrap those function call in an async block.

In case the job should start in a specific lifecycle state, you can use the handy lifecycle libs, so you have access to launchWhenCreated, launchWhenResumed or launchWhenStarted.

Related