shared abstract method

Job<T> shared({
  1. Object? key,
  2. String describe()?,
  3. JobObserver? observer,
})

Creates a handle that finishes with the outcome of this job and cannot reach it: one branch of a job continued in several.

A job is continued once, by one then or by handles of this: a call on a job that then has continued throws a StateError before anything is made. Each handle is cancelled independently of the others and carries the same value, so a resource it holds is closed by code that waits for every branch, not by each branch.

The handle has no body: it ends with the Done or Failed of this job, or Cancelled with a ChainCancelReason as soon as this job accepts a cancellation, and waits while this job refuses or holds one. It does not start a job of Job.deferred. On a job that has finished or accepted a cancellation already it ends on the next microtask, not inside the call.

The handle is a root job that inherits nothing, with its own optional observer, which hears JobObserver.onFinish and not JobObserver.onStart. Without describe its description is shared.

final text = Job<String>((ctx) async => 'hello');
final length = text.shared().then<int>((ctx, text) => text.length);
final loud = text.shared().then((ctx, text) => text.toUpperCase());
length.cancel(); // text and loud run on
print(await loud.value); // HELLO

See A handle for each branch on the chains page, and A job's name on the observing page for key and describe.

Implementation

Job<T> shared({
  Object? key,
  String Function()? describe,
  JobObserver? observer,
});