How to run workmanager immediately

Viewed 6774

In my android app i have a functionality by which a user can sync data (saved in sqlite) by pressing Sync button some where in Drawer menu. On click of sync button i starts the service and data gets synced to server.

But now i am using work manager to sync data. My question is how can we start work manager immediately on a button click.

I am creating Onetime request. some time it triggers but not other times.

4 Answers

WorkManager 2.7.0 introduces the concept of expedited work. Expedited work starts immediately and complete within a few minutes. here the doc

OneTimeWorkRequestBuilder<T>().apply {
    setInputData(inputData) 
 setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
}.build()

Here and here are "advanced" WorkManager guide/ medium post which goes over this.

In July 2020, Ben Weiss (Android Developer Relations at Google) said

We recommend you use WorkManager to execute long running immediate tasks. / Just make sure to make it a foreground service by using setForeground/ setForegroundAsync.

This specifies that the WorkRequest is long-running or otherwise important. In this case, WorkManager provides a signal to the OS that the process should be kept alive if possible while this work is executing.

docs

Calls to setForegroundAsync must complete before a ListenableWorker signals completion by returning a ListenableWorker.Result.

Under the hood, WorkManager manages and runs a foreground service on your behalf to execute this WorkRequest, showing the notification provided in ForegroundInfo.

Upd: The right way is to separate your logic from worker and call it from worker or from UI as needed. As Nurseyit pointed WM is not for immediate tasks. Also there is RxWorker from android.arch.work:work-runtime-ktx see docs which can easily wrap Rx network request or facade.

This can be used as quickfix or coding experiment: You can cancel enqueued Work by button and enqueue it again next line. Work Manager will try to launch this new Worker as soon as possible. While button is pressed app is foreground so there is a good chance that Work will run immediately. This way also will not clutter Worker's by extracting task logic to separate class, checking that in-Worker task instance is not running, cancelling, waiting for immediate task, etc.

Related