[英]Why Android lifecycleScope can be automatically cancelled
在閱讀這篇關於生命周期感知型 CoroutineScope 的帖子時,我閱讀了以下內容:
每個 Lifecycle 都帶有一個 LifecycleScope,它可以讓你啟動協程,一旦 Lifecycle 達到 DESTROYED state 就會自動取消。
我正在閱讀lifecycle-runtime-ktx.aar
中的源代碼,並試圖弄清楚 lifecycleScope(在 Fragment 或 Activity 中訪問)在被銷毀時如何被取消。
任何人都可以指出為什么 lifecycleScope 可以自動取消嗎? 這部分的源代碼在哪里。 謝謝!
Activity
& Fragment
在內部使用LifecycleCoroutineScope
,然后通過lifecycle.addObserver
掛鈎到組件的Lifecycle
周期。
如果您檢查LifecycleCoroutineScopeImpl
,
你會看到這個:
if (lifecycle.currentState == Lifecycle.State.DESTROYED) {
coroutineContext.cancel()
}
和
if (lifecycle.currentState <= Lifecycle.State.DESTROYED) {
lifecycle.removeObserver(this)
coroutineContext.cancel()
}
簡而言之,
觀察者被添加到組件中,如果lifecycle.currentState
低於Lifecycle.State.DESTROYED
則正在運行的協程將自動取消。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.