[英]How to allow only single executed task using streams or buffering stream event while executing long operation
I have some process which can be called periodically and forcibly.我有一些可以定期强制调用的过程。 The process can take some time.
该过程可能需要一些时间。 I need to disallow to start next
automatic task
until forcible task
is still executing, or I need to disallow the forcible task
until automatic task
is still executing (ie only one active task is allowed).我需要在
forcible task
仍在执行之前禁止启动下一个automatic task
,或者我需要在automatic task
仍在执行之前禁止forcible task
(即只允许一个活动任务)。 Yes, I understand that I can use some _isBusy
flag to define if task is still executing and skip adding to sink.是的,我知道我可以使用一些
_isBusy
标志来定义任务是否仍在执行并跳过添加到接收器。 But maybe there is a more elegant solution using streams (rxdart)?但也许有一个使用流(rxdart)的更优雅的解决方案? Moreover I would like if events not be missed but buffered so when the active task is completed, the next event is taken from
_controller.stream
.此外,我想如果事件不会被错过而是缓冲,所以当活动任务完成时,下一个事件来自
_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;
}
}
}
I looked at rxdart reference , but I can't find the elegant method.我查看了rxdart 参考,但找不到优雅的方法。
If I was to say it, you can where
.如果我要说的话,你可以
where
。
_controller.stream.where((_) => !_isBusy).listen((_) async {
await _execTask();
});
After some experience I got I found out that each event in stream is processed one by one.经过一些经验,我发现 stream 中的每个事件都是一个一个处理的。 So when one event is still processing the second one is waiting its turn in stream and more over
sent events are not missing
!因此,当一个事件仍在处理时,第二个事件正在等待轮到 stream 并且
sent events are not missing
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.