Flutter中stream学习
- 概述
- Stream的基础概念
- stream的常用方法
-
- Stream.fromFuture(Future<T> future)
- Stream.fromFutures(Iterable<Future<T>> futures)
- Stream.fromIterable(Iterable<T> elements)
- Stream.periodic(Duration period, [T computation(int computationCount)?])
- Stream<T> take(int count)
- Stream<T> takeWhile(bool test(T element))
- Stream<T> where(bool test(T event))
- Stream<T> distinct([bool equals(T previous, T next)])
- Stream<T> skip(int count)
- Stream<T> skipWhile(bool test(T element))
- Stream<S> map<S>(S convert(T event))
- Stream<S> expand<S>(Iterable<S> convert(T element))
- Stream的分类
概述
Stream 主要应用于 Flutter 的异步操作,在其他编程语言中也存在;Stream 提供了一种接受事件队列的方法,可通过 listen 进行数据监听,通过 error 接收失败状态,通过 done 来接收结束状态;
Stream的基础概念
Stream:表示一个可以接收异步事件的数据源。可以生成一个或多个值。StreamController:控制Stream,可以向其添加事件、错误以及关闭它。StreamSubscription:表示对Stream的监听,可以用来取消订阅。Sink:用来向Stream添加数据、错误、以及关闭。
stream的常用方法
Stream.fromFuture(Future future)
Stream通过Future对象创建新的单订阅流, 当Future对象完成时会触发 data / error, 然后已done事件结束
Future<String> getDate() async {
await Future.delayed(const Duration(seconds: 3));
return "当前时间为${DateTime.now()}";
}
void testStreamFromFuture() {
Stream.fromFuture(getDate()).listen((event) {
print("testStreamFromFuture============$event");
}).onDone(() {
print("testStreamFromFuture==========done 结束");
});
}
输出结果:

Stream.fromFutures(Iterable<Future> futures)
Stream 通过一系列的 Future 创建新的单订阅流,每个 Future 都会有自身的 data / error 事件, 当这一系列的 Future 均完成时,Stream 以 done 事件结束;若 Futures 为空,则 Stream 会立刻关闭;其分析源码,很直接的看到是将每一个 Future 事件监听完之后才会执行的微事件结束;
源码代码:
factory Stream.fromFutures(Iterable<Future<T>> futures) {
_StreamController<T> controller =
new _SyncStreamController<T>(null, null, null, null);
int count = 0;
// Declare these as variables holding closures instead of as
// function declarations.
// This avoids creating a new closure from the functions for each future.
void onValue(T value) {
if (!controller.isClosed) {
controller._add(value);
if (--count == 0) controller._closeUnchecked();
}
}
void onError(Object error, StackTrace stack) {
if (!controller.isClosed) {
controller._addError(error, stack);
if (--count == 0) controller._closeUnchecked();
}
}
// The futures are already running, so start listening to them immediately
// (instead of waiting for the stream to be listened on).
// If we wait, we might not catch errors in the futures in time.
for (var future in futures) {
count++;
future.then(onValue, onError: onError);
}
// Use schedule microtask since controller is sync.
if (count == 0) scheduleMicrotask(controller.close);
return controller.stream;
}
示例代码:
var datas = [getDate(), getDate(), getDate()];
Stream.fromFutures(datas).listen((event) {
print("testStreamFromFutures============$event");
}).onDone(() {
print("testStreamFromFutures==========done 结束");
}

最低0.47元/天 解锁文章
1582

被折叠的 条评论
为什么被折叠?



