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 (i.e. only one active task is allowed). Yes, I understand that I can use some _isBusy
flag to define if task is still executing and skip adding to sink. But maybe there is a more elegant solution using streams (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
.
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;
}
}
}
After some experience I got I found out that each event in stream is processed one by one. So when one event is still processing the second one is waiting its turn in stream and more over sent events are not missing
!