BLoC stands for Business Logic Component. The application implementation pattern of using BLoC is called BLoC pattern.
BLoC stands for Business Logic Component. The application implementation pattern of using BLoC is called BLoC pattern. It was conceived by Cong Hui, Paolo Soares, and Wenfan Huang at Google.
BLoC is a way to centralize your business logic in a single class of your app using Streams, reducing the maintenance issues that could arise with multiple code bases. It was created with the intent of allowing you to share code between Flutter (mobile) and AngularDart (web) applications, but it can be used for clarity without necessarily sharing code.
The BLoC pattern was presented at DartConf 2018 with livecoding by Paolo and can be seen on YouTube.
Some notes about the pattern:
BLoC doesn’t assume a particular way to get access to the component. It might be with an InheritedWidget, by passing it down manually through constructors, or using some form of automatic dependency injection.
You should avoid having one BLoC as a parameter of another BLoC. Instead, plug only the required outputs to the applicable inputs.
Large apps need more than one BLoC. A good pattern is to use one top-level component for each screen, and one for each complex-enough widget. Too many BLoCs can become cumbersome, though. Also, if you have hundreds upon hundreds of observables (streams) in your app, that has a negative impact on performance. In other words: don’t over-engineer your app.
In a hierarchy of BLoCs, the top-level (screen) BLoC is normally responsible for plugging streams of children BLoCs to each other.
BLoC is compatible with server logic. The pattern doesn’t force you to reimplement that logic on the client (like Flux/Redux would). Just wrap the server-side logic with a component.
One disadvantage that stems from the asynchronicity of streams is that when you build a StreamBuilder, it always shows initialData first (because it is available synchronously) and only then does it show the first event coming from the Stream. This can lead to a flash (one frame) of missing data. There are ways to prevent this — stay tuned for a more detailed article. p.s. If using rxdart version 0.19.0 and above, you can just use ValueObservable for outputs and the flash of async is no longer an issue.
The inside of the BLoC is often implemented in a purely functional-reactive way (no auxiliary state, pure transformations of one stream to another). But don’t feel obligated to do it this way. Sometimes, it’s easier and more readable/maintainable to express the business logic through hybrid imperative-functional approach.
References: