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

问题描述 投票:0回答:1

我有一些可以定期强行调用的过程。该过程可能需要一些时间。我需要禁止启动下一个automatic task,直到forcible task仍在执行,或者我需要禁止forcible task,直到automatic task仍在执行(即,仅允许one活动任务)。是的,我知道我可以使用一些_isBusy标志来定义任务是否仍在执行,并跳过添加到接收器的操作。但是,也许还有使用流(rxdart)的elegant解决方案?此外,我希望如果事件不会丢失而是被缓冲,那么当活动任务完成时,下一个事件将从_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;
    }        
  }
}
flutter stream rxdart
1个回答
0
投票

我看过rxdart reference,但找不到优雅的方法。

如果我这么说,可以where

_controller.stream.where((_) => !_isBusy).listen((_) async {
    await _execTask();
});
© www.soinside.com 2019 - 2024. All rights reserved.