[英]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.