Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform work manager tasks in sequence (when you don't have all work at the same time)

I want to upload some objects to a server. I'm using work manager and uniqueWork to avoid uploading duplicate objects. There is a constraint on the work so that they only operate when there is internet connectivity. The problem is I want each of these objects to upload one at a time, but all the work happens at once.

I know that I can use beginWith and workContinuations to perform work in sequence, but unfortunately multiple objects can be created at different times, so I do not have access to all the work at the time of creating the work.

val workRequest = OneTimeWorkRequestBuilder<UploadWorker>()
            .setConstraints(networkConstraint)
            .build()
WorkManager.getInstance()
            .enqueueUniqueWork(uniqueName, ExistingWorkPolicy.KEEP, workRequest)

I assumed enqueue meant that all the work would happen one at a time like a queue. Is there a way to make it work that way?

like image 419
Myk Avatar asked Oct 28 '22 13:10

Myk


1 Answers

You can use WorkManager's UniqueWork construct to be able to enqueue work so that it is executed only once. The Unique work is identified by the uniqueName.

In your case you should use a different ExistingWorkPollicy, as explained in the documentation: ExistingWorkPollicy.APPEND. This ensure that your new request is appended after other requests using the same uniqueName (this actually creates a chain of work).

val workRequest = OneTimeWorkRequestBuilder<UploadWorker>()
            .setConstraints(networkConstraint)
            .build()
WorkManager.getInstance()
            .enqueueUniqueWork(uniqueName, ExistingWorkPolicy.APPEND, workRequest)
like image 165
pfmaggi Avatar answered Oct 31 '22 10:10

pfmaggi