如何在执行长操作时只允许使用流或缓冲流事件的单个执行任务

How to allow only single executed task using streams or buffering stream event while executing long operation

我有一些进程可以周期性地强制调用。该过程可能需要一些时间。我需要禁止开始下一个 automatic task 直到 forcible task 仍在执行,或者我需要禁止 forcible task 直到 automatic task 仍在执行(即只有 允许一个 个活动任务)。是的,我知道我可以使用一些 _isBusy 标志来定义任务是否仍在执行并跳过添加到接收器。但也许有一个更优雅的解决方案使用流(rxdart)?此外,我 想要 如果事件没有丢失但被缓冲,那么当活动任务完成时,下一个事件取自 _controller.stream

class Processor {
  bool _isBusy;
  final _controller = StreamController<int>.broadcast();

  Processor() {
    _controller.stream.listen((_) async {
      if (!_isBusy) {
        await _execTask(); // execute long task
      }
    });
  }

  void startPeriodicTask() {
    Stream.periodic(duration: Duration(seconds: 15)).listen((_) {
      _controller.sink.add(1);
    })
  }

  void execTask() {
    _controller.sink.add(1);
  }

  void _execTask() async {
    try {
      _isBusy = true;
      // doing some staff
    } finally {
      _isBusy = false;
    }        
  }
}

我看了rxdart reference,没找到优雅的方法

如果我要说,你可以where

_controller.stream.where((_) => !_isBusy).listen((_) async {
    await _execTask();
});

经过一些经验,我发现流中的每个事件都是一个接一个地处理的。因此,当一个事件仍在处理时,第二个事件正在流中等待轮到它,并且更多 sent events are not missing!