Skip to content

//workflow/com.squareup.workflow1/Worker/run

run

[jvm]
Content
abstract fun run(): Flow<OutputT>
More info

Returns a Flow to execute the work represented by this worker.

Flow is “a cold asynchronous data stream that sequentially emits values and completes normally or with an exception”, although it may not emit any values. It is common to use workers to perform some side effect that should only be executed when a state is entered – in this case, the worker never emits anything (and will have type Worker).

Coroutine Context

When a worker is started, a coroutine is launched to collect the flow. When the worker is torn down, the coroutine is cancelled. This coroutine is launched in the same scope as the workflow runtime, with a few changes:

  • The dispatcher is always set to Unconfined to minimize overhead for workers that don't care which thread they're executed on (e.g. logging side effects, workers that wrap third-party reactive libraries, etc.). If your work cares which thread it runs on, use withContext or flowOn to specify a dispatcher.
  • A CoroutineName that describes the Worker instance (via toString) and the key specified by the workflow running the worker.

Exceptions

If a worker needs to report an error to the workflow running it, it must not throw it as an exception – any exceptions thrown by a worker’s Flow will cancel the entire workflow runtime. Instead, the worker’s OutputT type should be capable of expressing errors itself, and the worker’s logic should wrap any relevant exceptions into an output value (e.g. using the catch operator).

While this might seem restrictive, this design decision keeps the BaseRenderContext.runningWorker API simpler, since it does not need to handle exceptions itself. It also discourages the code smell of relying on exceptions to handle control flow.