Bloc: Cannot call yield from callback in Bloc (similar to #194)

Created on 7 May 2019  路  3Comments  路  Source: felangel/bloc

@override
  Stream<TimerState> mapEventToState(AbstractEvent event) async* {
   switch (event.name()) {
      case TimerEvents.StartTimerEvent:
        const oneSec = const Duration(seconds: 1);
        int start = 60;
        Timer.periodic(oneSec, (Timer timer) async* {
          if (start < 1) {
            timer.cancel();
          } else {
            debugPrint("start" + start.toString());
            yield MainModule().get<TimerStartedState>(additionalParameters: {'gameTime': start});
            start--;
          }
        });
        break;
         ..............

In the above example I would like to yield a state for every second. Yield is not working in the callback function of Timer.perodic(...). How do we handle yielding state in such scenario?

I guess question very similar to #194 but not sure how to apply await for in the above case.

Thanks for your help.

question

Most helpful comment

I've been struggling with this issue for hours until I searched here. Thank you for the perfect example!

All 3 comments

Hi @hivesey 馃憢
Thanks for opening an issue!

Regarding your question, I would recommend checking out the flutter_bloc_with_stream example.

Instead of using the async callback within mapEventToState to yield a new state, you should create a subscription and dispatch events asynchronously so that you don't block the event loop.

Hope that helps! 馃憤

Hi Felangel,

Thanks a lot, your example was helpful.
Resolved the issue by dispatching a separate event (from the original event) that in turn yields the state.

Thanks again!

I've been struggling with this issue for hours until I searched here. Thank you for the perfect example!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Reidond picture Reidond  路  3Comments

abinvp picture abinvp  路  3Comments

ricktotec picture ricktotec  路  3Comments

zjjt picture zjjt  路  3Comments

wheel1992 picture wheel1992  路  3Comments