Sub topic 12
Controlling concurrency with bloc_concurrency transformers
A Bloc receives events faster than async handlers can finish them. This chapter covers what happens when a second event arrives while the first handler is still running, and how to pick the behavior you want.
This chapter assumes you can write a Bloc with on<Event> handlers, that you know async/await and Dart Streams, and that you have read the chapters on async state and events.
What happens by default
Since bloc 8, every on<E> handler runs concurrently by default. If a user taps a button twice, two handler invocations run at the same time. Both can emit states, and their results can interleave in any order.
Consider a search box. The user types "fl", then "flu". Two requests start. If the "fl" request is slow and finishes last, its results overwrite the newer ones. The screen then shows results for a query the user no longer sees.
Each on<E> registration takes an optional transformer. A transformer is a function that receives the stream of events of type E and a mapper, which runs your handler for one event. It returns a stream of results. Changing the transformer changes how overlapping events are scheduled.
The bloc_concurrency package ships four transformers. Add it to pubspec.yaml next to flutter_bloc.
The four transformers
| Transformer | Behavior when a new event arrives mid-handler | Typical use |
|---|---|---|
| `concurrent()` | Starts the new handler immediately. Both run. | Independent work, such as marking different items as read |
| `sequential()` | Queues the new event. It runs after the current handler finishes. | Writes that must keep their order |
| `droppable()` | Ignores the new event. | Submit buttons, refresh actions |
| `restartable()` | Cancels the running handler and starts the new one. | Search, autocomplete, filters |
The next sections cover each transformer.
Replace nothing above; the diagram follows below.
restartable: only the latest event matters
The search example from the plan uses restartable(). When a new SearchQueryChanged arrives, the handler for the previous one is cancelled.
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
sealed class SearchEvent {}
final class SearchQueryChanged extends SearchEvent {
SearchQueryChanged(this.query);
final String query;
}
class SearchBloc extends Bloc<SearchEvent, List<String>> {
SearchBloc(this._search) : super(const []) {
on<SearchQueryChanged>(_onQueryChanged, transformer: restartable());
}
final Future<List<String>> Function(String query) _search;
Future<void> _onQueryChanged(
SearchQueryChanged event,
Emitter<List<String>> emit,
) async {
emit(await _search(event.query));
}
}Cancelling a handler does not cancel your Future. The _search call for "fl" still runs to completion on the network. What restartable() guarantees is that the cancelled handler's later emit calls are ignored. The stale result never reaches the state.
droppable: ignore duplicates
droppable() fits actions where a second trigger during processing is a mistake. A double-tapped "Place order" button is the classic case.
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
enum CheckoutStatus { idle, submitting, done }
sealed class CheckoutEvent {}
final class OrderSubmitted extends CheckoutEvent {}
class CheckoutBloc extends Bloc<CheckoutEvent, CheckoutStatus> {
CheckoutBloc(this._placeOrder) : super(CheckoutStatus.idle) {
on<OrderSubmitted>(_onSubmitted, transformer: droppable());
}
final Future<void> Function() _placeOrder;
Future<void> _onSubmitted(
OrderSubmitted event,
Emitter<CheckoutStatus> emit,
) async {
emit(CheckoutStatus.submitting);
await _placeOrder();
emit(CheckoutStatus.done);
}
}Without droppable(), two taps would place two orders. Disabling the button in the UI helps, but the Bloc should not rely on the UI for this guarantee.
sequential: preserve order
sequential() queues events and processes them one at a time, in arrival order. Use it when each handler depends on the result of the previous one, or when the server expects writes in order. Examples are appending to a remote list or saving successive edits to one document.
on<NoteEdited>(_onNoteEdited, transformer: sequential());The cost is latency. Event 5 waits for events 1 to 4. If one handler hangs, everything behind it hangs too. Give network calls a timeout.
Setting a default for the whole Bloc
A transformer applies to one on<E> registration. Handlers for different event types are independent of each other, even if each uses sequential(). A sequential() handler for A does not wait for a handler for B.
To change the default for every handler without repeating transformer:, set Bloc.transformer once at startup.
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
Bloc.transformer = sequential<dynamic>();
runApp(const MaterialApp(home: Scaffold()));
}A per-handler transformer: still overrides this global value.
Debouncing with a custom transformer
restartable() does not wait before starting. For a search box, you usually also want to hold events briefly, so that a request starts only after the user pauses typing. A transformer is a plain function, so you can write your own. The stream_transform package provides debounce and switchMap.
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:stream_transform/stream_transform.dart';
EventTransformer<E> debounceRestartable<E>(Duration duration) {
return (events, mapper) => events.debounce(duration).switchMap(mapper);
}Use it like the built-in ones:
on<SearchQueryChanged>(
_onQueryChanged,
transformer: debounceRestartable(const Duration(milliseconds: 300)),
);debounce drops events that are followed by another within 300 ms. switchMap then cancels the previous handler, as restartable() does. This pairing is the usual search-as-you-type setup.
Choosing a transformer
Ask what the user expects if they trigger the same action twice quickly.
- Only the latest matters (search, filter, tab switch):
restartable(). - A repeat is a mistake (submit, pay, refresh):
droppable(). - Every event counts and order matters (ordered writes):
sequential(). - Every event counts and order does not matter: keep
concurrent().
Common errors
- Using
restartable()for a write. Cancelling the handler does not undo the request that is already in flight. The server may apply the write while the Bloc ignores the outcome. Userestartable()for reads. - Awaiting the wrong thing after cancellation. Code after a cancelled
awaitstill runs. Onlyemitis silenced. Side effects such as writing to a database still happen. - Expecting
sequential()to order across event types. It orders only events of one registration. IfAandBmust be serialized together, handle them with one event type, or use a shared base event with oneon<Base>handler. - Forgetting that Cubits have no transformers. A Cubit method is an ordinary function call. If you need
droppable()orrestartable()behavior, move to a Bloc. This is a common reason to switch from Cubit to Bloc. - Stuck
droppable()handlers. A handler that never completes blocks all later events of that type. Always handle errors and timeouts.
Testing a transformer
A concurrency rule is behavior, so test it. This test sends two OrderSubmitted events and expects one submitting and one done state. The _placeOrder stand-in takes 10 ms, so the second event arrives while the first is still running.
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
blocTest<CheckoutBloc, CheckoutStatus>(
'drops the second submit while the first is running',
build: () => CheckoutBloc(
() => Future<void>.delayed(const Duration(milliseconds: 10)),
),
act: (bloc) => bloc
..add(OrderSubmitted())
..add(OrderSubmitted()),
wait: const Duration(milliseconds: 50),
expect: () => [CheckoutStatus.submitting, CheckoutStatus.done],
);
}If you replace droppable() with concurrent(), the expectation fails. The emitted list becomes [submitting, done] only once if the state values repeat (Bloc skips equal consecutive states), so check the number of calls to _placeOrder with a counter as well when you need certainty.
Exercise
A FilterBloc handles FilterChanged events by calling a slow, read-only API. Users change filters rapidly, and the screen sometimes shows results for an older filter. Which transformer fixes this, and why does it work even though the old request is not aborted?
Show answer
Use restartable() on the on<FilterChanged> handler. When a new event arrives, the previous handler is cancelled, and any emit it calls afterwards is ignored. The old request still finishes on the network, but its result never reaches the state, so only the latest filter's results are shown. It is safe here because the API call is read-only.
Exercise
Two handlers in one Bloc, on<Save> and on<Delete>, both use sequential(). A Save is running and a Delete arrives. Does the Delete wait? How would you make them wait for each other?
Show answer
No. Each on<E> registration has its own transformer pipeline, so Delete starts immediately. To serialize them, make Save and Delete subclasses of one sealed base event, register a single on<DocumentEvent> handler with sequential(), and switch on the event type inside it.