Search code examples
androidxandroid-workmanager

How do I chain unique work in WorkManager?


I have just discovered Unique Work which is apparently:

a powerful concept that guarantees that you only have one instance of work with a particular name at a time.

However, I can't figure out how to chain another piece of work after this.

val workRequest = OneTimeWorkRequestBuilder<MyWorker>().build()
val operation = workManager.enqueueUniqueWork(UNIQUE_WORK_NAME, ExistingWorkPolicy.REPLACE, workRequest)
// Can't do anything with operation and ensureUniqueWork doesn't take `workContinuation`

With the alternative construct, I can't use Unique Work, but this works:

val workRequest = OneTimeWorkRequestBuilder<MyWorker>().build()
var workContinuation = workManager.beginWith(workRequest)

val workRequestTwo = OneTimeWorkRequestBuilder<MyWorkerTwo>().build()
workContinuation = workContinuation.then(work)

workContinuation.enqueue()

Solution

  • You can use beginUniqueWork, the function takes a list of sequential work instead of calling .then. You are effectively giving the unique work name to the entire chain (3rd argument), not just a single work.

    val workRequestOne = ...
    val workRequestTwo = ...
    val workRequests = listOf(workRequestOne, workRequestTwo)
    workManager.beginUniqueWork("Unique work name", ExistingWorkPolicy.REPLACE, workRequests).enqueue()