简体   繁体   English

Android。 如何在不阻塞 UI 的情况下更正启动协程?

[英]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.我也在使用 MVVM。 In the documentation I read viewModelScope.launch { } :在文档中,我阅读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.如果文档说viewModelScope.launch { }会在不阻塞当前线程的情况下启动一个新的协程,为什么还要在这里再次launch{}

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?这样的构造(在 viewModelScope.launch 中启动)在某些情况下有用吗? Maybe I don't understand something, please help me.也许我不明白的东西,请帮助我。

Writing写作

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

is enough to launch a coroutine and execute a suspend function without blocking UI.足以启动协程并执行暂停 function 而不会阻塞 UI。

The launch within launch is used to launch tasks in parallel, for example: launch内的launch用于并行启动任务,例如:

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

task1() and task2() are suspend functions and will execute in parallel. task1()task2()suspend函数,将并行执行。

But if we write like the following:但是如果我们像下面这样写:

viewModelScope.launch {
   task1()
   task2()
}

task2() will wait until task1() is completed and then will start execution. task2()将等待task1()完成,然后开始执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM