Coroutine未在延迟之后执行视图模型

发布于 2025-02-10 06:19:14 字数 269 浏览 0 评论 0原文

我需要在ViewModel中执行一些推迟操作,因此我写下以下内容:

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫性小仙女 2025-02-17 06:19:14

正如@Darshan在关闭活动之后所说,ViewModel将清除,所有依赖ViewModel的操作都将取消,但是如果您想要一个不依赖此ViewModel和此活动的操作,则必须使用ProcessLifeCycleOwenr
添加androidx.lifecycle:LifeCycle-process:2.4.1到应用程序build> build.gradle file,然后使用

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

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 does not depend on 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")
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文