Nominalista
Nominalista

Reputation: 4840

How to chain new work to already enqueued work with WorkManager?

Let's say we have two workers: WorkerA and WorkerB. Now WorkerB can't be started before Worker is finished. Normally we would chain these two workers:

WorkManager.getInstance()
    .beginWith(workA)
    .then(workB)
    .enqueue()

But the problem is the we don't know exact moment when we can start WorkerB (we only that that it has to wait for WorkerA).

There are actually two cases:

  1. We want to start WorkerB when WorkerA has started, but it's not finished yet.
  2. We want to start WorkerB after WorkerA has finished.

In a perfect world, WorkManager would have an option to rather wait for some work or to chain to already existing work.

I thought about starting WorkerB from WorkerA before it will end doing job, but I'm not sure if accessing WorkManager from Work before returning Result is a good practice.

Upvotes: 0

Views: 814

Answers (1)

Rahul
Rahul

Reputation: 21104

When you create a chain of work, WorkerB will only start after WorkerA has completed successfully. If WorkerA fails, then WorkerB will also be marked as a failure.

If you want to start WorkerB when WorkerA has started, you can just enqueue WorkerB in WorkerA's doWork() method. Please keep in mind that both Workers are decoupled at that point.

Upvotes: 1

Related Questions