[英]Kotlin coroutine scope definition
Imagine that I have a coroutine scope called CryptographyScope
:想象一下,我有一个名为CryptographyScope
的协程范围:
object CryptographyScope : CoroutineScope {
override val coroutineContext: CoroutineContext =
Dispatchers.IO + CoroutineName("CryptographyScope")
}
So, in many places in my application I call CryptographyScope.async
.因此,在我的应用程序的许多地方,我调用CryptographyScope.async
。
CryptographyScope.async {
cryptographyService.decrypt(value)
}
What happens when one of the cryptographyService.decrypt(value)
fails and throws an exception?当cryptographyService.decrypt(value)
失败并抛出异常时会发生什么? Does it cancel every coroutine that uses CryptographyScope
in the application at the moment of execution?它是否会在执行时取消应用程序中使用CryptographyScope
每个协程?
Should the CryptographyScope be a singleton? CryptographyScope 应该是单例吗?
CoroutineScope defines a scope where you contain, delimit and keep track of all concurrent operations and tying them to the lifecycle of your application entity. CoroutineScope 定义了一个范围,您可以在其中包含、分隔和跟踪所有并发操作,并将它们与应用程序实体的生命周期联系起来。
I was going to call decrypt
through the custom scope I had created CryptographyScope
.我打算通过我创建的自定义范围CryptographyScope
调用decrypt
。 But, this isn't right since I don't have a any entity with defined lifecycle so won't be able to avoid leak happening.但是,这是不对的,因为我没有任何具有定义生命周期的实体,因此将无法避免发生泄漏。
The correct thing to do is:正确的做法是:
fun decryptAll() = coroutineScope {
async {
cryptographyService.decrypt(value1)
}
async {
cryptographyService.decrypt(value2)
}
}
GlobalScope.launch {} starts a new coroutine in the 'global' scope and launch {} starts a new coroutine in a CoroutineScope. GlobalScope.launch {} 在“全局”范围内启动一个新的协程,而 launch {} 在 CoroutineScope 中启动一个新的协程。
eg.例如。
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")
}
in the above snippet, the line at 4. will only execute when both coroutines defined inside runBlocking {} have been completed.在上面的代码片段中,4. 处的行仅在 runBlocking {} 中定义的两个协程都已完成时才会执行。
Now let try running the same code with GlobalScope.launch {}:现在让我们尝试使用 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.")
}
in above snippet 4. This line will execute even if the coroutines inside runBlocking did not complete.在上面的代码段 4 中。即使 runBlocking 中的协程没有完成,这一行也会执行。
However, the coroutines launched in the above example are running in a separate 'global' scope, where runBlocking has no control over.但是,上面示例中启动的协程在单独的“全局”范围内运行,runBlocking 无法控制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.