run method

  1. @override
Future<T> run()
override

Executes the computation and returns the computation result (or throws the exception), or throws the CancellationException exception.

Implementation

@override
Future<T> run() async {
  if (_isStarted) {
    throw StateError('The computation can be run only once');
  }

  _isStarted = true;
  if (_isTerminationRequested) {
    throw CancellationException();
  }

  if (_token != null) {
    _token!.throwIfCanceled();
  }

  var hasResult = false;
  T? result;
  unawaited(() async {
    try {
      await Future<void>.delayed(Duration.zero);
      result = await _zone.run(() {
        return Task.run(token: _token, _computation);
      });
      hasResult = true;
    } catch (e, s) {
      if (_error == null) {
        _error = e;
        _stackTrace = s;
      }
    }

    if (!_completer.isCompleted) {
      _completer.complete();
    }
  }());

  await _completer.future;
  if (_isTerminationRequested) {
    throw CancellationException();
  } else if (_error != null) {
    Error.throwWithStackTrace(_error!, _stackTrace ?? StackTrace.empty);
  } else if (hasResult) {
    return result as T;
  } else {
    throw StateError('Computation ended without result');
  }
}