我正在努力寻找一种在 Flutter 中以动态间隔时间定期发出流的方法。我不确定,这真的可能还是不可能。一种解决方法可能是取消旧的定期流并使用新的时间间隔重新初始化它,但我的带有 asyncMap 的定期流没有取消选项。我可以使用具有取消方法的 stream.listen 但我特意需要 asyncMap 将 Future 事件转换为流。在这种情况下,我可以做什么,请给我建议。
我的代码片段 -
int i = 0;
int getTimeDiffForPeriodicEvent() {
i++;
return (_timeDiffBetweenSensorCommands * commandList.length + 1) * i;
}
StreamBuilder(
stream: Stream.periodic(
Duration(seconds: maskBloc.getTimeDiffForPeriodicEvent()))
.asyncMap((_) async => maskBloc.getDataFromMask()),
builder: (context, snapshot) {
return Container();
},
);
这是不可能的Stream.periodic
,但您也许可以创建一个类,该类可以通过使用async*
和创建一个可以基于某些可变变量启动流和睡眠的类yield
:
class AdjustablePeriodStream {
Duration period;
AdjustablePeriodStream(this.period);
Stream<void> start() async* {
while (true) {
yield null;
print('Waiting for $period');
await Future.delayed(period);
}
}
}
这将允许相当容易地改变时期:
Future<void> main() async {
final ten = Duration(milliseconds: 10);
final twenty = Duration(milliseconds: 20);
final x = AdjustablePeriodStream(ten);
x.start().take(5).listen((_) {
print('event!');
x.period = (x.period == ten ? twenty : ten);
});
}
您可以在此处查看示例输出:
https://dartpad.dev/6a9cb253fbf29d8adcf087c30347835c
event!
Waiting for 0:00:00.020000
event!
Waiting for 0:00:00.010000
event!
Waiting for 0:00:00.020000
event!
Waiting for 0:00:00.010000
event!
Waiting for 0:00:00.020000
它只是在等待 10 到 20 毫秒之间切换(大概您还有其他一些想要用于此的机制)。您可能还需要某种方式来取消流(这将退出while (true)
循环),但我在这里省略了它以保持代码简短和具体。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句