synchronous_future.dart 1.86 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

/// A [Future] whose [then] implementation calls the callback immediately.
///
/// This is similar to [new Future.value], except that the value is available in
/// the same event-loop iteration.
///
/// ⚠ This class is useful in cases where you want to expose a single API, where
/// you normally want to have everything execute synchronously, but where on
/// rare occasions you want the ability to switch to an asynchronous model. **In
15 16
/// general use of this class should be avoided as it is very difficult to debug
/// such bimodal behavior.**
17 18 19 20 21 22 23 24 25 26
class SynchronousFuture<T> implements Future<T> {
  /// Creates a synchronous future.
  ///
  /// See also [new Future.value].
  SynchronousFuture(this._value);

  final T _value;

  @override
  Stream<T> asStream() {
27
    final StreamController<T> controller = StreamController<T>();
28 29 30 31 32 33
    controller.add(_value);
    controller.close();
    return controller.stream;
  }

  @override
34
  Future<T> catchError(Function onError, { bool test(Object error) }) => Completer<T>().future;
35 36

  @override
37
  Future<E> then<E>(FutureOr<E> f(T value), { Function onError }) {
38
    final dynamic result = f(_value);
39
    if (result is Future<E>)
40
      return result;
41
    return SynchronousFuture<E>(result as E);
42 43 44
  }

  @override
45
  Future<T> timeout(Duration timeLimit, { FutureOr<T> onTimeout() }) {
46
    return Future<T>.value(_value).timeout(timeLimit, onTimeout: onTimeout);
47
  }
48 49

  @override
50
  Future<T> whenComplete(FutureOr<dynamic> action()) {
51
    try {
52
      final FutureOr<dynamic> result = action();
53
      if (result is Future)
54
        return result.then<T>((dynamic value) => _value);
55 56
      return this;
    } catch (e, stack) {
57
      return Future<T>.error(e, stack);
58 59
    }
  }
60
}