Bloc: Add possibility to configure initial event

Created on 7 Feb 2020  路  2Comments  路  Source: felangel/bloc

Is your feature request related to a problem? No.
I don't like the way we add an initial event to the bloc, to add an event to the bloc right at the creation of it we have to add the cascade operator ..add to the creation of the bloc. I think the lib should have more clarity of this process.

Describe the solution you'd like
What i suggest is to create initialEvent (kind of similar to initialState) and if set the bloc will emit this event at its startup

Looking at the counter example it will be somethink like that:

class CounterBloc extends Bloc<CounterEvent, int> {
  @override
  int get initialState => 0;

  @override
  int get initialEvent => CounterEvent.increment;

  @override
  Stream<int> mapEventToState(CounterEvent event) async* {
    switch (event) {
      case CounterEvent.decrement:
        yield state - 1;
        break;
      case CounterEvent.increment:
        yield state + 1;
        break;
    }
  }
}

And the bloc will have some kind of logic to emit the first event before all things.

I know the lib is great enough that can handle what i want differently, but i think this proposed way will add some clarity to the bloc code.

Thanks for the great and hard work!

question

All 2 comments

Hi @rodrigobastosv 馃憢
Thanks for opening an issue!

Adding th event via cascade operator is slightly different from what you're proposing. When using the cascade operator from the create callback of BlocProvider you are only adding the event to the bloc when the BlocProvider widget is created. With your proposal, the event will be added as soon as the bloc is created which makes the bloc slightly less reusable. In my opinion, it's best to let the presentation layer determine when/what event to add to the bloc because the bloc doesn't make assumptions about the context in which it's being used.

In either case, I feel initialEvent is a bit unnecessary because you can just call add from the bloc constructor if you want an event to be added immediately when the bloc is created.

Let me know what you think and thanks for the awesome feedback!

I guess you are right @felangel .

Thanks for the fast reply and for the great work!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rsnider19 picture rsnider19  路  3Comments

1AlexFix1 picture 1AlexFix1  路  3Comments

abinvp picture abinvp  路  3Comments

timtraversy picture timtraversy  路  3Comments

krusek picture krusek  路  3Comments