add<T> method

Future<T> add<T>(
  1. Task<T> task, {
  2. int priority = 0,
  3. dynamic key,
})

Implementation

Future<T> add<T>(
  Task<T> task, {
    int priority = 0,
    dynamic? key,
  }) async {

  final c = Completer<T>();
  final job = () async {
    _pendingCount += 1;
    _intervalCount += 1;

    try {
      final operation = (_timeout == Duration.zero)
        ? task()
        : task().timeout(_timeout!,
          onTimeout: () {
            if (_throwOnTimeout) {
              throw TimeoutException('task timed out');
            }
            return null;
          } as FutureOr<T> Function()?
        );

      final result = await operation;
      emit(QueueEventAction.completed, result);
      c.complete(result);
    } on TimeoutException catch (error) {
      emit(QueueEventAction.error, error);
      c.completeError(error);
    } catch (error) {
      emit(QueueEventAction.error, error);
      c.completeError(error);
    }
    _next();
  };

  try {
    _queue.enqueue(job, priority: priority, key: key);
    emit(QueueEventAction.add);
  } catch (error) {
    emit(QueueEventAction.error, error);
    c.completeError(error);
  }

  _tryToStartAnother();

  return c.future;
}