flutterblocclean-architectureflutter-blocevent-driven-design

Flutter BLoC - Bloc vs Cubit event driven state management advantages


What are the actual advantage(s) of Bloc over Cubit?

In addition to traceability (which you can also achieve with appropriate logging in Cubit), and advanced event transformations (I can't think of any "advanced" event transformations that Cubit can't do, since there is always a way to do it with Cubit. And if you're using clean architecture, domain/data layer can help with complex data manipulations).

Sharing and sourcing events

These are the things that I'm looking for that should be able to do with Bloc since these things can't be actually done with Cubit. However, it appears that these are impossible (or is it?) because adding event on a Bloc requires you to identify the actual Bloc where the event will be added. bloc.add(YourEvent()).

Also, event sharing is somewhat debatable because this can lead to a bad architecture/hard to maintain.

For event sourcing, I can't find in the docs if this is possible (reversing back to a specific past state?).

Am I missing something here?


Solution

  • As far as I know reversing to past state can be easily done when you have immutable states regardless of whether it is bloc or cubit. Having immutable states allows you to store list of states and restore whenever you need a specific state.

    Bloc has no advantages over cubit but rather different purpose. In cubit you have action=>response (function=>states) whereas in bloc you have streams.

    What cubit cannot do?

    For example you can have two events being processed concurrently when using bloc (since bloc 7.20) but you cannot call two functions simultaneously on cubit.

    Sharing events

    You can share events implementation between different blocs because you have to specify what events bloc implements.

    class MyBlocA extends Bloc<MyEvents, StatesA>
    
    class MyBlocB extends Bloc<MyEvents, StatesB>
    

    If I understood correctly, what you want to do is to process a single event in two different blocs, which you cannot do because event is emitted to a specific bloc. So it requires two calls:

    blocA.add(EventA);
    blocB.add(EventA);
    

    Depending on your case you might listen to state of MyBlocA inside MyBlocB. This way whenever event for MyblocB appears, the action would depend on the state of MyBlocA.