Bloc: Stream waiting and blocking other events using Bloc in Flutter

Created on 22 Oct 2020  路  3Comments  路  Source: felangel/bloc

class EditorBloc extends Bloc<BookEvent, BooksState> {

  @override
  BooksState get initialState => BooksLoading();

  EditorBloc();

  Stream<BooksState> _loadBooks() async* {
await future.delay(Duration(seconds:1s,(){return Future.value(0)}))
  }

  Stream<BooksState> _saveBooks(Gym gym, Sector sector, BookHistory booksHistory) async* {
    // Some code
  }

  Stream<BooksState> _addBooks(Gym gym, Sector sector, BookHistory booksHistory) async* {
    // Some code
  }

  @override
  Stream<BooksState> mapEventToState(BooksState currentState, BookEvent event) async* {

    if (event is LoadBooks) {
      yield* _loadBooks(event.gym, event.sector);
    } else if(event is SaveBooks) {
      yield BooksLoading();
      yield* _saveBooks(event.gym, event.sector, event.booksHistory);
    } else if (event is AddBook) {
      yield* _addBooks(gym, sector, booksHistory)
    }
  }
}

if I add the three event same time, it seems that is will be block the event and not async , can deal witch event not block the steam?

bloc question

Most helpful comment

You need to import rxdart to use those operators 馃憤

All 3 comments

Hi @yaminet1024 馃憢
Thanks for opening an issue!

This is how bloc works by default (each event is processed in the exact order it was received). If you want to override this behavior you can override transformEvents and apply switchMap or flatMap depending on the desired functionality.

  @override
  Stream<Transition< BookEvent, BooksState >> transformEvents(
    Stream< BookEvent > events,
    TransitionFunction< BookEvent, BooksState > transitionFn,
  ) {
    return events.flatMap(transitionFn);
  }

Closing for now but feel free to comment with additional questions and I'm happy to continue the conversation 馃憤

Hi @yaminet1024 馃憢
Thanks for opening an issue!

This is how bloc works by default (each event is processed in the exact order it was received). If you want to override this behavior you can override transformEvents and apply switchMap or flatMap depending on the desired functionality.

  @override
  Stream<Transition< BookEvent, BooksState >> transformEvents(
    Stream< BookEvent > events,
    TransitionFunction< BookEvent, BooksState > transitionFn,
  ) {
    return events.flatMap(transitionFn);
  }

Closing for now but feel free to comment with additional questions and I'm happy to continue the conversation 馃憤

Thank you very much for your answer, but I find that Stream< BookEvent > events does not have switchMap or flatMap method in flutter

You need to import rxdart to use those operators 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

abinvp picture abinvp  路  3Comments

shawnchan2014 picture shawnchan2014  路  3Comments

RobPFarley picture RobPFarley  路  3Comments

Reidond picture Reidond  路  3Comments

hivesey picture hivesey  路  3Comments