lightbulb_outline Please take our October 2018 developer survey. Start survey

Worker

public abstract class Worker
extends ListenableWorker

java.lang.Object
   ↳ androidx.work.ListenableWorker
     ↳ androidx.work.Worker


The basic object that performs work. Worker classes are instantiated at runtime by WorkManager and the doWork() method is called on a background thread. In case the work is preempted for any reason, the same instance of Worker is not reused. This means that doWork() is called exactly once per Worker instance.

Summary

Public constructors

Worker(Context context, WorkerParameters workerParams)

Public methods

abstract ListenableWorker.Result doWork()

Override this method to do your actual background processing.

Data getOutputData()
final ListenableFuture<ListenableWorker.Payload> onStartWork()

Override this method to start your actual background processing.

void setOutputData(Data outputData)

Call this method to pass a Data object as the output of this Worker.

Inherited methods

Public constructors

Worker

public Worker (Context context, 
                WorkerParameters workerParams)

Parameters
context Context

workerParams WorkerParameters

Public methods

doWork

public abstract ListenableWorker.Result doWork ()

Override this method to do your actual background processing.

Returns
ListenableWorker.Result

getOutputData

public Data getOutputData ()

Returns
Data the output Data set by the Worker.

onStartWork

public final ListenableFuture<ListenableWorker.Payload> onStartWork ()

Override this method to start your actual background processing. This method is called on the main thread.

Returns
ListenableFuture<ListenableWorker.Payload> A ListenableFuture with the ListenableWorker.Payload of the computation. If you cancel this Future, WorkManager will treat this unit of work as failed.

setOutputData

public void setOutputData (Data outputData)

Call this method to pass a Data object as the output of this Worker. This result can be observed and passed to Workers that are dependent on this one. In cases like where two or more OneTimeWorkRequests share a dependent WorkRequest, their Data will be merged together using an InputMerger. The default InputMerger is OverwritingInputMerger, unless otherwise specified using the OneTimeWorkRequest.Builder.setInputMerger(Class) method.

This method is invoked after onStartWork and returns ListenableWorker.Result.SUCCESS or a ListenableWorker.Result.FAILURE.

For example, if you had this structure:

 WorkManager.getInstance(context)
             .beginWith(workRequestA, workRequestB)
             .then(workRequestC)
             .enqueue()
This method would be called for both workRequestA and workRequestB after their completion, modifying the input Data for workRequestC.

Parameters
outputData Data: An Data object that will be merged into the input Data of any OneTimeWorkRequest that is dependent on this one, or Data.EMPTY if there is nothing to contribute