gpt4 book ai didi

flutter - 如何在Dart中使用async *函数

转载 作者:行者123 更新时间:2023-12-03 03:21:55 40 4
gpt4 key购买 nike

我正在使用flutter_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()的语法糖,将await放入try-catch块是使用.catchError的语法糖。您可以用一种方法完成的事情可以用另一种方法完成。
  • 在使用.then() / .catchError()的第一个版本中,您的函数不返回任何内容。
  • 您的回调将不起作用,因为您在其中使用了yield*,但是尚未使用sync*async*指定回调。为避免名称冲突,yield关键字要求使用它们(与await要求使用asyncasync*的函数相同)。

  • 这是应该与 .then().catchError()一起使用的版本:

    Stream<BlocState> _handleEvent(BlocEvent event) async* {
    yield* await _repository.getData(event.id).then((response) async* {
    yield* _processResult(response);
    }).catchError((e) async* {
    yield* _handleError(e);
    });
    }

    注意,回调不需要使用 yield*;他们可以直接返回 Stream:

    Stream<BlocState> _handleEvent(BlocEvent event) async* {
    yield* await _repository.getData(event.id).then((response) {
    return _processResult(response);
    }).catchError((e) {
    return _handleError(e);
    });
    }

    但是(正如其他所有人都指出的那样),使用 await而不是 Future API可以简化整个过程(尤其是因为我们已经在使用 await了):

    Stream<BlocState> _handleEvent(BlocEvent event) async* {
    try
    response = await _repository.getData(event.id);
    yield* _processResult(response);
    } catch (e) {
    yield* _handleError(e);
    }
    }

    有关可运行示例,请参见 https://dartpad.dartlang.org/fc1ff92e461754bdb35b998e7fbb3406

    关于flutter - 如何在Dart中使用async *函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62198091/

    40 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com