Reputation: 1237
How to throttle events in bloc? Let's say, I want to trigger file save on user input, but perform file system access not more often than once per 100ms?
Example bloc event handler:
on<StoreFile>(_handleStoreEvent);
Upvotes: 3
Views: 2518
Reputation: 625
You can define a custom EventTransformer which handles how events are processed
EventTransformer<E> throttleDroppable<E>(Duration duration) {
return (events, mapper) {
return droppable<E>().call(events.throttle(duration), mapper);
};
}
Make sure to import package:stream_transform to use the throttle api.
Then simply pass it in the bloc
on<StoreFile>(_handleStoreEvent, transformer: throttleDroppable(Duration(milliseconds: 100)));
For reference see here: Flutter bloc infinite_list example
Upvotes: 1
Reputation: 1237
Each handler have an optional transformer:
field which can do throttling (and much more).
Using rxdart you can implement throttling yourself:
on<StoreFile>(
_handleStoreEvent,
transformer: (events, mapper) => events.throttleTime(Duration(milliseconds: 100)).switchMap(mapper),
);
I wrote the bloc_event_transformers package to do popular transforms like throttle and debounce to reduce the boilerplate in my apps. It can be used like that:
on<StoreFile>(
_handleStoreEvent,
transformer: throttle(Duration(milliseconds: 100)),
);
Upvotes: 9