flutterdartreactive-programmingblocstate-management

How to throttle events in bloc?


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);

Solution

  • 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)),
    );