简体   繁体   English

退出屏幕时的网络调用 - Android 协程

[英]Network call when exiting the screen - Android coroutines

I am trying to implement a UI in a fragment, where user can make all sorts of updates and I need send it over to backend when user EXITS the screen.我正在尝试在片段中实现一个 UI,用户可以在其中进行各种更新,当用户退出屏幕时,我需要将其发送到后端。 (Batch update) (批量更新)

I am using MVVM pattern, where network calls are performed from viewmodel .我正在使用 MVVM 模式,其中网络调用是从 viewmodel 执行的。 Now, viewModelScope.launch won't work here, since as soon as user exits, the coroutine is canceled by onCleared() .现在, viewModelScope.launch在这里不起作用,因为一旦用户退出,协程就会被onCleared()取消。 For now, I added GlobalScope and it works but I have also come across this and this question现在,我添加了 GlobalScope 并且它有效,但我也遇到过这个和这个问题

Are there any other alternatives to accomplish this with Coroutines?是否有其他替代方案可以使用 Coroutines 完成此任务?

Coroutines are mostly recommended for work that should start immediately and is scoped to the lifecycle of a Fragment, Activity, ViewModel or any other object with a lifecycle .协程通常被推荐用于应该立即开始的工作,并且范围是 Fragment、Activity、ViewModel 或任何其他具有生命周期的对象的生命周期 Since the rest of the coroutine builders are tied to scopes, they wont accomplish what you are trying to do, since the user might leave your app at any given time.由于其余的协程构建器与作用域相关联,因此它们不会完成您想要做的事情,因为用户可能会在任何给定时间离开您的应用程序。

A better approach would be using WorkManager with CoroutineWorker , which isn't tied to your UIs or App lifespan and still takes the advantages of working with Coroutines.更好的方法是将WorkManagerCoroutineWorker一起使用,它与您的 UI 或应用程序生命周期无关,并且仍然可以利用使用 Coroutines 的优势。 With WorkManager , your work could be enqueued when the user leaves your designated screen and will be guaranteed to run once the constraints you specify are fulfilled (for example having internet connection).使用WorkManager ,您的工作可以在用户离开您指定的屏幕时进入队列,并且一旦您指定的约束得到满足(例如具有互联网连接),您的工作将被保证运行。 I recommend you to check Android's Guide to background processing if you are still making up your mind on which solution to use.如果您仍在决定使用哪种解决方案,我建议您查看Android 的后台处理指南

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM