Bloc: Yield State not from generator

Created on 10 Sep 2020  路  2Comments  路  Source: felangel/bloc

Hi,

I have a question, is it possible to yield a new State not from the mapEventToState pipeline?

I will explain,
Consider a bloc that has an internal subscription to a stream from some dependency of it.
The subscription is established in the bloc constructor.
When that stream emit event, I want to emit new Bloc State

Something like this:

   `   
 class MyBloc extends Bloc<BlocEvent, BlocState> {
 final AuthManager authManager;

   MyBloc({this.authManager}){
     _initializeAuthStream();
   }

  Stream<BlocState> mapEventToState(BlocEvent event){
    if(event is UserStateEvent){
      yield* _handleUserStateChanged(event);  //This eventually will emit new State 
    }
  }

  void _initializeAuthStream() {
     authManager.userStateStream.listen((userState) => {
       //How can I yield a state from here?

      //Currently I do like this:  
       add(UserStateEvent(state: userState)) //This will add new event to the bloc
    })
  }
}`

Thanks for your support

question

Most helpful comment

Hi @MotiBartov 馃憢

You can't directly yield a state from your onData callback, e.g: you can't do something like:
yield* authManager.userStateStream.listen((userState) async* { yield Authenticated(); }) since listen returns a StreamSubscription not a Stream.

Bloc's state should only be updated by yielding a new state from mapEventToState in response to an event. So your current approach is the correct one. 馃憤

All 2 comments

Hi @MotiBartov 馃憢

You can't directly yield a state from your onData callback, e.g: you can't do something like:
yield* authManager.userStateStream.listen((userState) async* { yield Authenticated(); }) since listen returns a StreamSubscription not a Stream.

Bloc's state should only be updated by yielding a new state from mapEventToState in response to an event. So your current approach is the correct one. 馃憤

Thanks @RollyPeres for taking the time to respond!

@MotiBartov closing this for now but feel free to comment with additional questions and I鈥檓 happy to continue the conversation 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

krusek picture krusek  路  3Comments

frankrod picture frankrod  路  3Comments

hivesey picture hivesey  路  3Comments

ricktotec picture ricktotec  路  3Comments

clicksocial picture clicksocial  路  3Comments