如何启动不应从作曲事件处理程序中取消的Coroutine

发布于 2025-01-25 19:39:20 字数 793 浏览 3 评论 0原文

我拥有代表一个“编辑数据”屏幕的组合:

@Composable
fun EditNodeScreen(
    vm: EditNodeViewModel,
    canceled: () -> Unit,
    accepted: (id: UUID) -> Unit
) {
    // ...
    Button(onClick = {
      val id = vm.save()
      accepted(id)
    }) {
      Text(text = "Save")
    }
}

editnodeviewmodel.save()实际上是一个悬挂函数,所以我不能只这样称呼它。

我能找到的说,我应该使用remamecoroutinesCope()创建一个Coroutine范围,然后使用它来启动Coroutine:

onClick = {
    coroutineScope.launch {
        val id = vm.save()
        accepted(id) // side question: do I have to switch back to Main context?
    }
}

但是文档 也表示将取消此coroutine如果组成分离。我做不是想要在开始后取消保存过程!

这仍然是正确的事情,还是有更好的方法?我应该使用globalscope.launch吗?

I have this composable that represents an "edit data" screen:

@Composable
fun EditNodeScreen(
    vm: EditNodeViewModel,
    canceled: () -> Unit,
    accepted: (id: UUID) -> Unit
) {
    // ...
    Button(onClick = {
      val id = vm.save()
      accepted(id)
    }) {
      Text(text = "Save")
    }
}

Except, EditNodeViewModel.save() is actually a suspend function, so I can't just call it like that.

What I can find says that I should create a coroutine scope with rememberCoroutineScope(), then use that to launch a coroutine:

onClick = {
    coroutineScope.launch {
        val id = vm.save()
        accepted(id) // side question: do I have to switch back to Main context?
    }
}

But the documentation also says that this coroutine will be canceled if the composition is detached. I do not want to cancel the save process once it is commenced!

Is this still the right thing to do, or is there a better way? Should I use GlobalScope.launch perhaps?

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

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

发布评论

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

评论(1

洋洋洒洒 2025-02-01 19:39:20

如果您必须处理应完成的操作,即使用户从屏幕上导航,请使用Workmanager

来自 docs

工人旨在用于可靠运行的工作
如果用户从屏幕上导航,应用程序退出或设备
重新启动。

使用加快工作立即开始任务。

If you have to handle an operation that should be completed even if the user navigates away from the screen, use WorkManager.

From the Docs,

WorkManager is intended for work that is required to run reliably even
if the user navigates off a screen, the app exits, or the device
restarts.

Use Expedited work to start the task immediately.

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