【问题标题】:Coroutine does not executed after delay in view model协程在视图模型延迟后不执行
【发布时间】:2022-11-18 16:41:37
【问题描述】:

我需要在 ViewModel 中执行一些延迟的操作,所以我写了以下内容:

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

如果我保持此活动打开,它会打印消息。但如果我在 3 秒内关闭活动,它不会打印任何内容。

【问题讨论】:

  • ViewModel 的生命周期与相关的 Fragment/Activity 相关联,当您退出 Activity 时它会被清除并且所有操作都被取消。

标签: android kotlin-coroutines


【解决方案1】:

正如@DarShan 在关闭活动后所说的那样,viewModel 将清除并且所有依赖于 ViewModel 的操作都将取消,但是如果您想要一个不依赖于此 ViewModel 和此活动的操作,则必须使用ProcessLifecycleOwenr。 添加androidx.lifecycle:lifecycle-process:2.4.1到appsbuild.gradle文件然后使用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2013-11-11
    相关资源
    最近更新 更多