Flutter BLoC: Transformers

Sajid Khan
Mindful Engineering
2 min readSep 14, 2022

TL;DR — Reduce boilerplate and fine-tune how your events should be processed within a bloc.

The below will require bloc_concurrency package.

Transformers dictate how your event will be processed within a bloc. They can help reduce boilerplate code and keep your code organized.

There are instances when a BLoC event needs to be debounced such as when we’re dealing with a search API where each text change triggers an API call. Other times, we need to maintain an exact sequence in which events were added such as adding music tracks to a playlist queue.

The bloc_concurrency package has four of these transformers and let’s look at each of them:

1. Restartable

Let’s have an event with a transformer and a corresponding event handler which tells us when the event starts and stops:

Note that we used a restartable transformer.

Our Event handler looks like this:

Since we used a restartable transformer for the event, all new SomeEvent events will cancel previous event handlers and thus will be treated as a single running event.

You can fire multiple SomeEvent events and the output to those will be:

2. Droppable

The droppable transformer ignores any new events while an event is running. Predictable, right?

With the same event handler _someEventHandler, now we get:

Thus, the event handler waits for the event to finish and ignores any new events until the current one finishes. This can be useful to avoid unnecessary calls when we’re already waiting for a response.

3. Sequential

The sequential transformer, as the name suggests, maintains the original sequence of events that they were added in.

With the same event handler _someEventHandler, now we get:

The sequential transformer can be helpful to maintain a queue of events.

4. Concurrent

The concurrent transformer is the default transformer that pushes events concurrently. Concurrency here means that the event handler prioritises work that can be done rather than waiting upon any blocking work.

With the same event handler _someEventHandler, now we get:

The concurrent transformer can have event overlap as seen in the output above and there is no way of determining event priority.

While this concludes the available transformers, you can build you own too!

Photo by Glen Carrie on Unsplash

Let’s say you wanted to debounce the sequential transformer:

This would mean that we can avoid multiple API calls for our search operation.

The rxdart package can help you get creative with your custom transformers.

That marks the beginning of your journey towards using, creating and customizing bloc transformers. Hope it helps you tackle structural challenges and reduce boilerplate.

--

--