How to implement PeriodicWorkRequest chain?

Viewed 1028

I study Android WorkManager, and fond one problem.

I have 2 Works, first of them fetch some data from server and second preload resources (depends on result of first work). I need doing this chains one time per hour.

I need something like:

workManager.beginWith(work1).then(work2)

But in WorkManger API I found chain only for OneTimeWorkRequest.

2 Answers

You cannot chain PeriodicWorkRequests. For your use-case you might consider using a OneTimeWorkRequest with a Worker that enqueues a copy of itself at the end of doWork() with an initial delay (to simulate periodicity).

That way you can still do chaining. I would tag all work requests consistently so you can getWorkInfosByTagLiveData() correctly.

Promoting Andrew's comment into an answer:

Google's had an open ticket to add this functionality (see here).

Google's official solution there was to create a periodic work request with an "chain initiation" worker, in that worker's doWork() define and enqueue a chain of one-time work requests.

Related