Issue
I have a task to synchronize Room DB data to the server every 2 hours in the background, for that the best option I found is Work Manager, but there is a problem I have two tables one for images and the second for the form data, first Worker Task is to upload all the images to the server using Retrofit Multipart and then upload form data from another table. There are basically need two worker classes and I don't know to arrange them to complete the whole task.
Thanks in advance.
Solution
There are multiple ways to handle this.
- Use the same
Worker
to handle both use cases like -
override suspend fun doWork(): Result {
// uploading images
withContext(Dispatcher.IO) { uploadImages() }
// uploading form data
withContext(Dispatcher.IO) { uploadFormData() }
return Result.success()
}
- Enqueue
FormDataUploadWorker
after theImageUploadWorker
is finished
(Not recommended though):
override suspend fun doWork(): Result {
// assuming there is some sort of result returned
val isSuccess = withContext(Dispatcher.IO) { uploadImages() }
if (isSuccess) {
// Should be OneTimeWorkRequest, better if it is expedited
WorkManager.getInstance(applicationContext).enqueue(FormDataUploadWorker)
}
return Result.success()
}
- WorkManager also supports chained tasks (recommended, IMO).
WorkManager.getInstance(applicationContext)
.beginWith(ImageUploadWorker)
.then(FormDataUploadWorker)
.enqueue()
Answered By - DarShan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.