如何在Flutter的Stream.periodic事件中使用动态间隔时间

How to use dynamic interval time in Stream.periodic event in Flutter

我正在努力寻找一种在 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 是不可能的,但您也许可以创建一个 class,它可以使用 async* 和 [= 根据一些可变变量启动流和睡眠15=]:

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) 循环),但我在这里省略它以保持代码简短和具体。