Search code examples
androidkotlin-coroutinesandroid-viewmodelandroid-mvvmcoroutinescope

Android. How to correct launch coroutine without blocking UI?


I'm new in coroutines. And I'm trying add it to my project. Also I'm using MVVM. In the documentation I read viewModelScope.launch { }:

Launches a new coroutine without blocking the current thread

But at the same time, I often see code constructs like this:

viewModelScope.launch {
   launch {
      // call some suspend fun here
  }
}

Why is another launch{} here if the documentation says that viewModelScope.launch { } launches a new coroutine without blocking the current thread.

Wouldn't it be enough to write like this:

 viewModelScope.launch {
    // call some suspend fun here
  }

Could such a construction (launch inside viewModelScope.launch) be useful in some cases? Maybe I don't understand something, please help me.


Solution

  • Writing

    viewModelScope.launch {
      // call some suspend fun here
    }
    

    is enough to launch a coroutine and execute a suspend function without blocking UI.

    The launch within launch is used to launch tasks in parallel, for example:

    viewModelScope.launch {
       launch {
          // call task 1
          task1()
       }
       launch {
          // call task 2
          task2()
       }
    }
    

    task1() and task2() are suspend functions and will execute in parallel.

    But if we write like the following:

    viewModelScope.launch {
       task1()
       task2()
    }
    

    task2() will wait until task1() is completed and then will start execution.