如何启动不应从作曲事件处理程序中取消的Coroutine
我拥有代表一个“编辑数据”屏幕的组合:
@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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您必须处理应完成的操作,即使用户从屏幕上导航,请使用
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,
Use Expedited work to start the task immediately.