Reputation: 1019
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?
Upvotes: 6
Views: 1838
Reputation: 6476
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)
Upvotes: 5