为什么 ViewModel 中的协程方法在离开 Fragment 后继续处理?
why coroutine method in ViewModel is continuing to process after leaving Fragment?
这是我在 Fragment onCreate() 中调用 updateProgress() 的方法
在向前导航到另一个 Activity 或 Fragment 之后,此 updateProgress 仍在继续工作。我怎么能阻止这个?
如果我正在导航到另一个 Activity 或 Fragment,我期待
应调用 ViewModel onCleared(),它将停止此更新
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
fun updateProgress() {
uiScope.launch {
delay(UPDATE_PROGRESS_INTERVAL)
updateCurrentProgramProgress()
contentRowsMutableData.postValue(contentRows)
updateProgress()
}
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
片段被销毁时调用onCleared
。如果您移动到另一个片段,前一个片段将保留在后台堆栈中(如果您使用 addToBackstack
),因此会暂停,但不会被销毁。
如果您想在片段暂停时停止处理数据,您可以让您的 ViewModel 实现 LifecycleObserver
接口,然后您将添加
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
// add code here to stop work
}
然后您也可以使用此恢复处理
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun start() {
// code here
}
但是,请注意,在片段暂停时工作可能是可取的,因此当用户 returns 到片段时,工作完成并且可以立即显示数据。这完全取决于您的具体情况。
这是我在 Fragment onCreate() 中调用 updateProgress() 的方法 在向前导航到另一个 Activity 或 Fragment 之后,此 updateProgress 仍在继续工作。我怎么能阻止这个? 如果我正在导航到另一个 Activity 或 Fragment,我期待 应调用 ViewModel onCleared(),它将停止此更新
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
fun updateProgress() {
uiScope.launch {
delay(UPDATE_PROGRESS_INTERVAL)
updateCurrentProgramProgress()
contentRowsMutableData.postValue(contentRows)
updateProgress()
}
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
片段被销毁时调用onCleared
。如果您移动到另一个片段,前一个片段将保留在后台堆栈中(如果您使用 addToBackstack
),因此会暂停,但不会被销毁。
如果您想在片段暂停时停止处理数据,您可以让您的 ViewModel 实现 LifecycleObserver
接口,然后您将添加
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
// add code here to stop work
}
然后您也可以使用此恢复处理
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun start() {
// code here
}
但是,请注意,在片段暂停时工作可能是可取的,因此当用户 returns 到片段时,工作完成并且可以立即显示数据。这完全取决于您的具体情况。