How to implement PeriodicWorkRequest chain?
Asked Answered
M

3

10

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.

Mareah answered 31/10, 2018 at 21:19 Comment(2)
did you find out the way to do periodic work request in chain?Whitehot
No, but for this case I use periodic worker which start chain of OneTimeWorkRequests, looks ugly, but working for meMareah
W
6

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.

Welterweight answered 26/5, 2019 at 15:48 Comment(0)
A
0

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.

Anglonorman answered 24/10, 2020 at 20:16 Comment(0)
P
0

I was able do to it through creating a simple PeriodicWorkRequest with its doWork() implements the following

override suspend fun doWork(): Result {
    ...
    WorkManager.getInstance(context).beginWith(oneTimeWork1).then(oneTimeWork2).enqueue()
    Result.success()
}

Not ideal but this way it triggers the chain at its periodic interval

Protestantism answered 16/12, 2022 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.