Coroutine未在延迟之后执行视图模型
我需要在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如@Darshan在关闭活动之后所说,ViewModel将清除,所有依赖ViewModel的操作都将取消,但是如果您想要一个不依赖此ViewModel和此活动的操作,则必须使用
ProcessLifeCycleOwenr
。添加
androidx.lifecycle:LifeCycle-process:2.4.1
到应用程序build> build.gradle
file,然后使用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 appsbuild.gradle
file and then use