[英]How to launch a coroutine that should never be canceled from a Compose event handler
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.除了,
EditNodeViewModel.save()
实际上是一个暂停 function,所以我不能那样调用它。
What I can find says that I should create a coroutine scope with rememberCoroutineScope()
, then use that to launch a coroutine:我能找到的是我应该使用
rememberCoroutineScope()
创建协程 scope ,然后使用它来启动协程:
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?我应该使用
GlobalScope.launch
吗?
If you have to handle an operation that should be completed even if the user navigates away from the screen, use WorkManager
.如果您必须处理即使用户离开屏幕也应该完成的操作,请使用
WorkManager
。
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.
WorkManager 适用于需要可靠运行的工作,即使用户离开屏幕、应用程序退出或设备重启也是如此。
Use Expedited work to start the task immediately.使用加急工作立即开始任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.