简体   繁体   English

如何启动一个永远不应该从 Compose 事件处理程序中取消的协程

[英]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

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. WorkManager 适用于需要可靠运行的工作,即使用户离开屏幕、应用程序退出或设备重启也是如此。

Use Expedited work to start the task immediately.使用加急工作立即开始任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Android Jetpack Compose 的可组合物中启动协程 - how to launch a coroutine inside a composable in Android Jetpack Compose 如何在不使用 init 的情况下从类中启动协程? - How to launch a coroutine from within a class without using init? Android kotlin 处理程序和协程启动(IO)组合不起作用 - Android kotlin handler and coroutine launch(IO) combination not working 从Handler启动AlertDialog - Launch AlertDialog from Handler 如何在协程中启动谷歌地图标记? - how to launch a Google Maps Marker inside a Coroutine? 如何使用片段管理器从 Jetpack Compose 中启动片段? - How to launch a Fragment from within Jetpack Compose with Fragment Manager? 如何从处理程序启动Intent或线程? - How do I launch an Intent or thread from a Handler? 有没有办法知道您的协程是否已从暂停中取消 function - Is there a way to know if your coroutine has been canceled from within a suspend function 接听或取消电话后,如何在BroadcastReceiver中停止处理程序? - How to stop handler inside BroadcastReceiver after phone call is answered or canceled? Android Jetpack Compose (Composable) 从协程获取字符串资源 - Android Jetpack Compose (Composable) Get String resources from Coroutine
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM