Home > Software engineering >  Coroutine does not executed after delay in view model
Coroutine does not executed after delay in view model

Time:06-25

I need to execute some postponed action in ViewModel, so I write the following:

fun doAction() {
    viewModelScope.launch() {
        delay(3000)
        Log.i("Tag", "I can not see this message")
        // some actions...
    }
}

It prints the message if I keep this activity open. But if I close the activity within 3 sec it does not print anything.

CodePudding user response:

As @DarShan said after close activity, viewModel will clear and all the actions that depend on viewmodel will cancel, but if you want an action that's not depend this viewmodel and this activity, you have to use ProcessLifecycleOwenr. add androidx.lifecycle:lifecycle-process:2.4.1 to apps build.gradle file and then use

ProcessLifecycleOwner.get().lifecycleScope.launch{
  delay(3000)
  Log.i("Tag", "I can not see this message")
}

CodePudding user response:

Since you are using ViewModelScope the scope will run out when ViewModel get destroyed. In your use case your should be using it a different scope which can last longer. You can try something like this :

fun doAction() {
    val scope = MainScope()
    scope.launch() {
        delay(3000)
        Log.i("Tag", "I can not see this message")
        // some actions...
    }
}
  • Related