Search code examples
androidandroid-workmanagerworkmanagers

How to queue tasks for Worker (WorkerManager API)?


I have a chain of requests

fun foo(){
....
WorkManager.getInstance(iC)
            .beginWith(downloadWorkRequest)
            .then(unzipWorkRequest)
            .then(deleteWorkRequest)
            .enqueue()
 .....
 }

This whole task (let's say) take 1 minute... Problem is that if I call this method a few times (for example 4 times) in one minute, so WorkManager really will start this task 4 times asynchronously.

I need that all this tasks will be executed synchronously (like queue).

How to do it?


Solution

  • You can use a unique work in this case with a ExistingWorkPolicy.APPEND

    fun foo(){
    ....
    WorkManager.getInstance(iC)
               .beginUniqueWork(
                   "my_unique_work_name",
                   ExistingWorkPolicy.APPEND,
                   downloadWorkRequest)
               .then(unzipWorkRequest)
               .then(deleteWorkRequest)
               .enqueue()
     .....
     }
    

    You can find an example of this in the WorkManager codelab.