Search code examples
androidkotlinandroid-room

Multiple work request in Work Manager for Periodic task


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.

    1. 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()
    }
    
    1. Enqueue FormDataUploadWorker after the ImageUploadWorker 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()
    }
    
    1. WorkManager also supports chained tasks (recommended, IMO).
    WorkManager.getInstance(applicationContext)
        .beginWith(ImageUploadWorker)
        .then(FormDataUploadWorker)
        .enqueue()