[英]Kotlin coroutine scope definition
想象一下,我有一个名为CryptographyScope
的协程范围:
object CryptographyScope : CoroutineScope {
override val coroutineContext: CoroutineContext =
Dispatchers.IO + CoroutineName("CryptographyScope")
}
因此,在我的应用程序的许多地方,我调用CryptographyScope.async
。
CryptographyScope.async {
cryptographyService.decrypt(value)
}
当cryptographyService.decrypt(value)
失败并抛出异常时会发生什么? 它是否会在执行时取消应用程序中使用CryptographyScope
每个协程?
CryptographyScope 应该是单例吗?
CoroutineScope 定义了一个范围,您可以在其中包含、分隔和跟踪所有并发操作,并将它们与应用程序实体的生命周期联系起来。
我打算通过我创建的自定义范围CryptographyScope
调用decrypt
。 但是,这是不对的,因为我没有任何具有定义生命周期的实体,因此将无法避免发生泄漏。
正确的做法是:
fun decryptAll() = coroutineScope {
async {
cryptographyService.decrypt(value1)
}
async {
cryptographyService.decrypt(value2)
}
}
GlobalScope.launch {} 在“全局”范围内启动一个新的协程,而 launch {} 在 CoroutineScope 中启动一个新的协程。
例如。
fun main() {
println("1. Let's start")
runBlocking {
launch {
delay(1000)
println("3. coroutine ONE")
}
launch {
delay(500)
println("2. coroutine TWO")
}
}
println("4. Only when the children inside runBlocking complete, execution follows on this line")
}
在上面的代码片段中,4. 处的行仅在 runBlocking {} 中定义的两个协程都已完成时才会执行。
现在让我们尝试使用 GlobalScope.launch {} 运行相同的代码:
fun main() {
println("1. with GlobalScope.launch {}")
runBlocking {
GlobalScope.launch {
delay(1000)
println("3. coroutine ONE ")
}
GlobalScope.launch {
delay(100)
println("2. coroutine TWO")
}
}
println("4. This line will execute even if the coroutines inside runBlocking did not complete.")
}
在上面的代码段 4 中。即使 runBlocking 中的协程没有完成,这一行也会执行。
但是,上面示例中启动的协程在单独的“全局”范围内运行,runBlocking 无法控制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.