Kotlin协程GlobalScope.launch与runBlocking [英] Kotlin coroutines GlobalScope.launch vs runBlocking

查看:388
本文介绍了Kotlin协程GlobalScope.launch与runBlocking的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法之间有什么区别吗?

Is there any difference between this two approaches?

runBlocking {
   launch(coroutineDispatcher) {
      // job
   }
}

GlobalScope.launch(coroutineDispatcher) {
   // job
}

推荐答案

runBlocking运行新的协程并中断当前线程,直到完成为止.协程不应该使用此功能.它旨在将常规的阻塞代码桥接到以挂起方式编写的库中,以用于主要功能和测试中.

runBlocking runs new coroutine and blocks current thread interruptibly until its completion. This function should not be used from coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.

// line 1
runBlocking {
   // line 2
   launch(coroutineDispatcher) {
      // line 3
   }
   // line 4
}
// line 5
someFunction()

如果使用runBlocking,则将按以下顺序执行代码行:

In case of using runBlocking lines of code will be executed in the next order:

line 1
line 2
line 4
line 3
line 5 // this line will be executed after coroutine is finished

全局作用域用于启动在整个应用程序生命周期内运行且不会过早取消的顶级协程.全局范围的另一种用法是在Dispatchers.Unconfined中运行的运算符,它们没有任何关联的工作. 应用程序代码通常应使用应用程序定义的CoroutineScope,不建议在GlobalScope实例上使用异步或启动.

Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely. Another use of the global scope is operators running in Dispatchers.Unconfined, which don't have any job associated with them. Application code usually should use application-defined CoroutineScope, using async or launch on the instance of GlobalScope is highly discouraged.

// line 1
GlobalScope.launch(coroutineDispatcher) {
   // line 2
}
// line 3
someFunction()

在使用GlobalScope.launch的情况下,将按以下顺序执行代码行:

In case of using GlobalScope.launch lines of code will be executed in the next order:

line 1
line 3
line 2

因此runBlocking会阻止当前线程,直到完成为止,而GlobalScope.launch不会.

Thus runBlocking blocks current thread until its completion, GlobalScope.launch doesn't.

这篇关于Kotlin协程GlobalScope.launch与runBlocking的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆