I'm working with Flutter Bloc and noticed that when I dispatch the same event multiple times in quick succession, Bloc emits multiple Loading states before transitioning to Success. This behavior seems expected, but I'm wondering if it's a practical concern in real-world applications.
Bloc code:
sealed class CategoryState {
const CategoryState();
}
final class CategoryInitial extends CategoryState {}
final class CategoryLoading extends CategoryState {}
final class CategorySuccess extends CategoryState {}
final class CategoryFailure extends CategoryState {}
Future<void> _onAddCategory(AddCategoryEvent event, Emitter<CategoryState> emit) async {
emit(CategoryLoading());
try {
await _categoryRepository.addCategory(event.categoryMap);
emit(CategorySuccess());
} catch (e) {
emit(CategoryFailure());
}
}
Triggering Events Rapidly:
bloc.add(AddCategoryEvent(categoryMap: categoryModelMap));
bloc.add(AddCategoryEvent(categoryMap: categoryModelMap));
bloc.add(AddCategoryEvent(categoryMap: categoryModelMap));
bloc.add(AddCategoryEvent(categoryMap: categoryModelMap));
Observed State Transitions (Log Output):
Transition: { currentState: CategoryInitial, event: AddCategoryEvent, nextState: CategoryLoading }
Transition: { currentState: CategoryLoading, event: AddCategoryEvent, nextState: CategoryLoading }
Transition: { currentState: CategoryLoading, event: AddCategoryEvent, nextState: CategoryLoading }
Transition: { currentState: CategoryLoading, event: AddCategoryEvent, nextState: CategoryLoading }
Transition: { currentState: CategoryLoading, event: AddCategoryEvent, nextState: CategoryLoading }
Transition: { currentState: CategoryLoading, event: AddCategoryEvent, nextState: CategorySuccess }
Transition: { currentState: CategorySuccess, event: AddCategoryEvent, nextState: CategorySuccess }
Would this ever happen in a real-world application, or is this just an artificial test case? If this is a concern, what is the best way to prevent redundant state emissions while still ensuring all events are processed?
Yes It is a practical concern in the real world. You can see user can spam the button adding multiple API calls at once. You can also see user typing really fast in the search field.
Bloc gives flexibility on treating these events in the form of transformers.
https://bloclibrary.dev/bloc-concepts/#advanced-event-transformations
Here Transformers allows you to control how events are processed, particularly when multiple events are added in quick succession. The bloc_concurrency package provides pre-built event transformers that help manage event handling efficiently.
Summary of those I know is bellow.
Transformer | Info |
---|---|
sequential() | Default, processes one event at a time |
debounce() | Waits before executing the latest event, Used for Live search, handling rapid user input |
others are restartable(), droppable()
Examples you can see here. https://medium.com/mindful-engineering/flutter-bloc-transformers-7b62c32d80f6