felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.79k stars 3.39k forks source link

Question: One big BLoC or a few smaller cubits? #3415

Closed enseitankad0 closed 1 year ago

enseitankad0 commented 2 years ago

Hi What's the best approach to make something like parent-children bloc architecture? Very often I face a problem when there is a need to establish communication between cubits or blocs.

Let's image a form where we would like to create a new user:

  1. User name
  2. User role (separate cubit, fetch all possible option from API)
  3. Calendar (separate cubit, a lot of calculations made)
  4. Apply button (main BLoC which is responsible to save new user).

First approach:

We need to get each cubit's state and emit new state when clicking on Apply button.

var role = context.read<RolesCubit>().state as RoleSelected;
var date = context.read<CalendarCubit>().state as DateSelected;
context.read<CreateUserBloc>.add(CreateNewUserEvent((role: role, date: date));

Pros:

Cons

Second approach:

context.read<CreateUserBloc>.add(DateChanged((newDate));
context.read<CreateUserBloc>.add(RoleChanged((newRole));
context.read<CreateUserBloc>.add(CreateNewUserEvent(());

Create one big BLoC which can do all responsibilities. Pros:

I hope I explained a problem in a simple way.

ghost commented 2 years ago

Disclaimer: I'm a new dev and I have been using this package for almost a year, any better answers or corrections are welcome.

I believe that using one big bloc is better.

I think the thought about splitting the code for easier maintenance of tests and cubits be reused in this case can lead to the opposite effects. At first it doesn't seems to cause any form of problem or complexity because we dealing with one simple form, but what if we have two or more ? Or what if our forms needs different behaviors from your UserRoleCubit and/or CalendarCubit ? What about create more tests because we have to test that validation difference between our forms ? What about the more code you are adding in the app because you need to pass your cubits ?

You can see how this can scale to a huge problem that can end in you refactoring your whole code.

felangel commented 1 year ago

I generally recommend having a bloc manage the state for a single feature/use-case. This way you'll have smaller blocs which are scoped to just the portion of the widget tree that needs them and they can be disposed automatically when no longer needed. Hope that helps 👍