ivanesi
ivanesi

Reputation: 1663

How to yield inside callback function?

Please read this bloc fragment:

if (event is TapVariant) {
  final bool isVariantCorrect = (correctVariantIndex == event.index);
  if (isVariantCorrect) {  
    yield CorrectVariant();
  } else {
    yield IncorrectVariant();
    Future.delayed(Duration(seconds: 1), () { 
      yield CorrectVariant();
    });
  }
}

I need to yield CorrectVariant from nested function.

I solved it this way:

    yield IncorrectVariant();
    await Future.delayed(Duration(seconds: 1), () {});
    yield CorrectVariant();

But I'm curious.

Upvotes: 2

Views: 2030

Answers (1)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126734

You already presented the best way to do it and here is why:

  • As you are in an async* function you have access to the await keyword, which allows you to handle future callbacks in the same scope.

  • If you were using yield in a sync* function, you could not wait for callbacks anyway as you are not running asynchronous code.


Return from the callback

As you are dealing with Future's, you can also return your value inside the callback like this:

yield 1;

// The following statement will yield "2" after one second.
yield await Future.delayed(Duration(seconds: 1), () {
  return 2;
});

Upvotes: 6

Related Questions