Nui*_*ibb 1 stream dart periodic-task flutter stream-builder
我正在努力寻找一种在 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();
},
);
Run Code Online (Sandbox Code Playgroud)
这对于 是不可能的,但您也许可以使用和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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将允许相当容易地更改周期:
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);
});
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看示例输出:
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
Run Code Online (Sandbox Code Playgroud)
它只是在等待 10 毫秒和 20 毫秒之间切换(大概您有其他想要用于此目的的机制)。您可能还需要某种方法来取消流(这将跳出循环while (true)),但我在这里省略了它以保持代码简短且具体。