Generators with yield*

Last updated: 12.09.2020 - 16:00 by Boehrsi

Generator functions in Dart are pretty useful, but it’s important to use them the right way. It’s required to use the yield* prefix for related method calls, as without the function won’t be called at all.
This leads to malfunctions and is also quite hard to debug, as it’s not obvious (no errors are thrown).

DO prefix async generator functions with yield*

Stream<State> mapEventToState(Event event) async* {
    yield* _requestData(event.id); // Good
}

Stream<State> _requestData(int id) async* {
    final data = await dataRepository.load(chatId);
    yield DataLoaded(data: data);
}

DON'T forget the prefixing

Stream<State> mapEventToState(Event event) async* {
    _requestData(event.id); // Bad, as this won't work and no error is thrown
}

Stream<State> _requestData(int id) async* {
    final data = await dataRepository.load(chatId);
    yield DataLoaded(data: data);
}