enqueueJob<T> method

  1. @protected
SoloJob<T> enqueueJob<T>(
  1. Job<T> job, {
  2. bool first = false,
  3. Policy policy = Policy.sequential,
})

Queues job and returns it, or the existing job found by Policy.droppable.

A job Policy.droppable may hand back to another caller refuses a plain then: every caller continues it through shared().

first puts the job at the head of the queue instead of the tail, past what is waiting and not past the running job. A replacement queued by Policy.restart waits at the tail like any other, so a job enqueued first after it starts ahead of it.

Policy.keepLatest and Policy.restart queue job before they cancel the jobs it replaces, whose onFinish and cancellation listeners run inside this call: a job they queue under the key replaces job in turn. A hook that does so on every cancellation, a replacement too, runs out of stack; such a hook leaves a ReplacedCancelReason alone.

Throws StateError if job was already enqueued or run, and ArgumentError if policy is not Policy.sequential and the job has no key, if job was created by another controller, or if Policy.droppable finds that key on a job of another result type. Every ArgumentError here is thrown before job is taken, so the job can be enqueued again.

After close the job finishes at once with Cancelled(closed), and a key held by another result type is not looked for at all — except by Policy.droppable during a SoloCloseMode.drain, which hands back a job with the key that the drain still runs, as before the close.

See Queue and policies on the jobs page.

Implementation

@protected
SoloJob<T> enqueueJob<T>(
  Job<T> job, {
  bool first = false,
  Policy policy = Policy.sequential,
}) {
  final impl = _own(job);
  if (policy != Policy.sequential && impl.key == null) {
    throw ArgumentError('Policy.${policy.name} requires a job key');
  }
  if (impl._taken ||
      impl._jobStatus != JobStatus.created ||
      _queue._jobs.contains(impl)) {
    throw StateError('$impl has already been enqueued or run');
  }
  // Looked up before the job is marked as enqueued, and the answer reused
  // below: a key shared with a job of another result type is the caller's
  // mistake, and `enqueueJob` must not bury the job it then refuses to hand
  // back. Nothing between here and the branch touches the queue. A closed
  // controller takes no new work, but a `drain` still runs what it had: a
  // duplicate found there is handed back as before the close, since its work
  // is going to be done, and only new work gets the closed answer.
  final duplicate = (!isClosed || _draining) && policy == Policy.droppable
      ? _lastJobWhere((other) => other.key == impl.key)
      : null;
  // The two jobs are compared with each other, not with `T`: the type
  // argument of this call is whatever the call site wrote down, and a
  // `SoloJob<void>` accepts any job at all — `void` is a top type, so
  // `is SoloJob<void>` is true of a `Job<String>` and the caller would
  // get somebody else's job back while its own work never ran.
  if (duplicate != null && duplicate._resultType != impl._resultType) {
    throw ArgumentError.value(
      '$job',
      'job',
      'key ${impl.key} is held by a job of result type '
          '${duplicate._resultType}, not ${impl._resultType}',
    );
  }
  // Set before anything can go wrong below: a job dropped by a closed
  // controller has been enqueued too, and one handle is one enqueue.
  impl._taken = true;
  // Any job of this call may be handed to the next caller of the key, so
  // every one of them refuses a plain `then` from the start, the first
  // caller's included: otherwise whether a caller throws would depend on
  // who came first.
  if (policy == Policy.droppable) impl._requireShared(_handedBack);
  if (isClosed && duplicate == null) {
    _debug(() => 'enqueue $impl: closed');
    impl._drop(
      Cancelled.by(
        reason: const ClosedCancelReason(),
        started: false,
        stackTrace: _closeStackTrace,
      ),
    );
    return impl;
  }
  // Found by [Policy.droppable] only.
  if (duplicate != null) {
    // A job of another policy is marked here, when it first has a second
    // caller, and before any code of the caller runs below; a `then` its
    // own caller took before stays.
    duplicate._requireShared(_handedBack);
    _debug(() {
      final name = '$duplicate';
      final line = 'enqueue $impl: duplicate of $name';
      final current = _current;
      // A droppable method called from inside the running job -- its
      // body, a child of it, its cleanup -- hands back that very job,
      // and a wait for it there is a wait for itself. A duplicate of a
      // queued job hands back that one, which starts only after the
      // running job ends, like any job queued from inside it. Who
      // called is not known here, so the line says what holds for any
      // caller.
      if (current == null) {
        return line;
      }
      if (identical(duplicate, current)) {
        return '$line, which is running: if awaited from inside $name, '
            'it waits for itself';
      }
      final running = '$current';
      return '$line, which is queued while $running is running: '
          'it starts after $running ends';
    });
    impl._drop(
      Cancelled.by(
        reason: const DuplicateCancelReason(),
        started: false,
        stackTrace: StackTrace.current,
      ),
    );
    // The type was checked before the job was marked as enqueued.
    return duplicate as SoloJob<T>;
  }
  // Queued before the others are cancelled, not after: cancelling one
  // runs its `onFinish` and its cancellation listeners synchronously, and
  // that code may queue a job of its own under the same key. Inserted
  // first, this job is the one such a call finds and replaces; inserted
  // afterwards, it would land behind that call and replace it instead,
  // and the job queued last would not be the one to run last.
  _queue._insert(impl, first: first);
  _debug(() {
    final line = 'enqueue $impl${first ? ' first' : ''}';
    final current = _current;
    // A method of the controller called from a running job -- its body,
    // a child of it, its cleanup -- queues a root job, and a job that
    // awaits it waits for good. Who called is not known here, so the line
    // says what holds for any caller.
    if (current == null) {
      return line;
    }
    final name = '$current';
    return '$line while $name is running: it starts after $name ends';
  });
  if (policy == Policy.keepLatest || policy == Policy.restart) {
    // What the cancelled jobs' code does to this one is the queue's usual
    // business from here: a cancellation removes it, a `close` drops it
    // with the rest.
    _queue.removeWhere(
      (other) => other.key == impl.key && !identical(other, impl),
      reason: const ReplacedCancelReason(),
    );
    // Unless that code took [job] out again: the running job is cancelled
    // for a job that is going to run, not for one that already ended.
    final current = _current;
    if (policy == Policy.restart &&
        !impl.isFinished &&
        current != null &&
        current.key == impl.key) {
      unawaited(current.cancel(reason: const ReplacedCancelReason()));
      // The line above it says the new job waits for the running one,
      // and from it alone a refused restart reads as `sequential`.
      _debug(() => 'restart: ${current._restartAnswer}');
    }
  }
  _schedulePump();
  return impl;
}