简体   繁体   English

如何在回调函数中产生收益?

[英]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.我需要从嵌套函数中产生 CorrectVariant。

I solved it this way:我是这样解决的:

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

But I'm curious.但我很好奇。

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.当您在async*函数中时,您可以访问await关键字,它允许您在同一范围内处理未来的回调。

  • If you were using yield in a sync* function, you could not wait for callbacks anyway as you are not running asynchronous code.如果您在sync*函数中使用yield ,无论如何您都无法等待回调,因为您没有运行异步代码。


Return from the callback从回调中返回

As you are dealing with Future 's, you can also return your value inside the callback like this:当您处理Future ,您还可以在回调中返回您的值,如下所示:

yield 1;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM