【发布时间】:2020-09-23 15:24:32
【问题描述】:
我正在使用 flutter_bloc 库。
在 bloc 中,mapEventToState 方法是一个 async* 函数,它返回 Stream<BlocState>。
从这个函数中,我正在调用其他 async* 这样的函数 yield* _handleEvent(event)
在这种方法中,我调用了一些 Future 返回函数,但在 Future then() 函数中它不会让我调用其他 yield* 函数。
这是一个例子:
Stream<BlocState> mapEventToState(BlocEvent event) async*{
yield* _handlesEvent(event); //This calls to worker method
}
Stream<BlocState> _handleEvent(BlocEvent event) async* {
_repository.getData(event.id).then((response) async* { //Calling Future returned function
yield* _processResult(response); //This won't work
}).catchError((e) async* {
yield* _handleError(e); //This won't work either
});
Response response = await _repository.getData(event.id); //This do works but I want to use it like above, is it possible?
yield* _processResult(response); //This do works
}
然而,问题是,如何在 dart 中结合 Future 和 Stream 。
我可以使用await _repository.getData 有效。但是我不会发现错误。
【问题讨论】:
-
使用简单的
await而不是then:var response = await _repository.getData(event.id); yield* _processResult(response); -
谢谢,我在我的问题中提到了这一点,我该如何捕捉这样的错误?我想使用 Future api 的内置 catch 错误。
-
使用普通的 try-catch - 什么不起作用?
-
谢谢,请参考下面我对@Candace 的回复
标签: flutter dart dart-async