Stream<T>.fromFuture 构造函数

Stream<T>.fromFuture(
  1. Future<T> future
)

从future创建一个新的单订阅流。

当future完成时,流将触发一个事件,无论是数据还是错误,然后通过完成事件关闭。

示例

Future<String> futureTask() async {
  await Future.delayed(const Duration(seconds: 5));
  return 'Future complete';
}

final stream = Stream<String>.fromFuture(futureTask());
stream.listen(print,
    onDone: () => print('Done'), onError: print);

// Outputs:
// "Future complete" after 'futureTask' finished.
// "Done" when stream completed.

实现

factory Stream.fromFuture(Future<T> future) {
  // Use the controller's buffering to fill in the value even before
  // the stream has a listener. For a single value, it's not worth it
  // to wait for a listener before doing the `then` on the future.
  _StreamController<T> controller =
      new _SyncStreamController<T>(null, null, null, null);
  future.then((value) {
    controller._add(value);
    controller._closeUnchecked();
  }, onError: (error, stackTrace) {
    controller._addError(error, stackTrace);
    controller._closeUnchecked();
  });
  return controller.stream;
}