Let’s build a small counter app to demonstrate the usage of the BLoC pattern.
Step 01: Create a React application and structure it.
First, we need to start by setting up a React app. I will name it bloc-counter-app. Also, I will be using
rxjs as well.
// Create React app
npx create-react-app bloc-counter-app// Install rxjs
yarn add rxjs
Then you need to remove all unnecessary code and structure the application as follows.
- Blocs — Keep all the bloc classes we need.
- Components — Keep the UI components.
- Utils — Keep utility files of the project.
Step 02: Implementation of the BLoC.
Now, let’s implement the BLoC class. The BLoC class will be responsible for implementing all subjects related to business logic. In this example, it is responsible for the counter logic.
So, I have created a file named
CounterBloc.js inside the bloc directory and used a pipe to pass the counter to the UI components.
As you can see, there is simple logic in this class. However, when an app grows in size, imagine the complexity if we do not separate the business logic.
Step 03: Adding more beauty to the BLoC by an intermediate class.
In this step, I will create the
StreamBuilder.js inside the utils directory to handle the counter request from the UI. Moreover, developers can handle errors and implement customer handlers within this.
AsyncSnapshot class, we can initialize a constructor, handle our data (check availability, etc. ), and handle errors. But in this example, I have only returned the data for ease of demonstration.
The initial data is passed into
AysncSnapshot class and stored in the snapshot state for each subscription. Then it will get rendered in the UI components.
Note: Ensure to unsubscribe from all the observables and dispose of the BLoCs upon unmounting UI components.
Step 04: Implementing UI components.
As you can see now,
decrease() methods are called directly within the UI component. However, output data is handle by a stream builder.
It is better to have an intermediate layer to implement custom handlers to handle errors.
app.js file, the BLoC is initialized using the
CounterBloc class. Thus, the
Counter component is used by passing the BLoC as a prop.
That’s it. Now you can treat your business logic as a separate entity outside your UI components and change it as you need.
To use and improve this example app please refer to the project repository and do not forget to make a PR. 😃