0

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. (Batch update)

I am using MVVM pattern, where network calls are performed from viewmodel . Now, viewModelScope.launch won't work here, since as soon as user exits, the coroutine is canceled by onCleared(). For now, I added GlobalScope and it works but I have also come across this and this question

Are there any other alternatives to accomplish this with Coroutines?

1 Answers1

0

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. 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. 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). I recommend you to check Android's Guide to background processing if you are still making up your mind on which solution to use.

mach
  • 1
  • 1
  • Yes, WorkManager is a great option but this work can't be deferred right? I need to show updated UI (fetching again from backend) when user re-enters that screen. I won't know when constraints are going to get fulfilled. – banaras Aug 26 '20 at 19:05
  • WorkManager fits perfect for deferred tasks. You can use an instance of `OneTimeWorkRequestBuilder` and call `setInitialDelay()` on the builder to set a specific minimum waiting time if needed. In your case, chances are constraints will be met right away since the user was using your app. Either way, with GlobalScope or WorkManager, you'll probably want to check if the deferred work is done. This is much more simpler with WorkManager, since you can get the status of your work via an id. With GlobalScope you'd need to implement a way to do that since it's a 'fire and forget' solution. – mach Aug 29 '20 at 18:33