我有一些可以定期强行调用的过程。该过程可能需要一些时间。我需要禁止启动下一个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;
}
}
}
我看过rxdart reference,但找不到优雅的方法。
如果我这么说,可以where
。
_controller.stream.where((_) => !_isBusy).listen((_) async {
await _execTask();
});