Chris G.
Chris G.

Reputation: 25954

Add delay constructing a Future

Playing with Dart, is it possible to create a delay constructing a Future?:

Future<String>.value("Hello").then((newsDigest) {
        print(newsDigest);
      }) // .delayed(Duration(seconds: 5))

Yes, this is possible:

factory Future.delayed(Duration duration, [FutureOr<T> computation()]) {
  _Future<T> result = new _Future<T>();
  new Timer(duration, () {
    try {
      result._complete(computation?.call());
    } catch (e, s) {
      _completeWithErrorCallback(result, e, s);
    }
  });
  return result;
}

Upvotes: 2

Views: 355

Answers (1)

attdona
attdona

Reputation: 18923

As you have already discovered Future.delayed constructor creates a future that runs after a delay:

From the docs:

Future<T>.delayed(
    Duration duration,
    [ FutureOr<T> computation()
]) 

The computation will be executed after the given duration has passed, and the future is completed with the result of the computation.

If computation returns a future, the future returned by this constructor will complete with the value or error of that future.

For the sake of simplicity, taking a future that complete immediately with a value, this snippet creates a delayed future that complete after 3 seconds:

import 'dart:async';

main() {
  var future = Future<String>.value("Hello");

  var delayedFuture = Future.delayed(Duration(seconds: 3), () => future);

  delayedFuture.then((value) {
    print("Done: $value");
  });
}

Upvotes: 1

Related Questions