Search code examples
androidkotlinkotlin-coroutinesandroid-architecture-components

Calling multiple suspend functions in Activity/Fragment


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?


Solution

  • 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.