Search code examples
androidandroid-viewmodelkotlin-coroutines

why coroutine method in ViewModel is continuing to process after leaving Fragment?


Here is my method I am calling updateProgress() in Fragment onCreate() and after navigating forward to another Activity or Fragment this updateProgress is still continue to work. How can I stop this ? I was expecting if I am navigating to another Activity or Fragment ViewModel onCleared() should be called and it will stop this update


 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()
  }


Solution

  • The onCleared is called when the fragment is destroyed. If you move to another fragment, the previous one will remain in the backstack (if you used addToBackstack) and thus is paused, but not destroyed.

    If you want to stop processing data when the fragment is paused, you can have your ViewModel implement the LifecycleObserver interface, then you would add

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop() {
        // add code here to stop work
    }
    

    You can then also resume processing with this

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start() {
        // code here
    }
    

    However, note that working while the fragment is paused may be desirable, so when the user returns to the fragment the work is complete and data can be shown immediately. It all depends on your specific circumstances.