1

Is there an easy way to sort the event queue of a flutter bloc by a value of the event class? E.g. I have a class MyEvent with a int property and the event queue looks like this:

[MyEvent(5), MyEvent(3), MyEvent(7), AnotherEvent(), MyEvent(2), MyEvent(1)]

I want to transform the event queue/stream so that the event with the lowest int property is executed first -> [MyEvent(3), MyEvent(5), MyEvent(7), AnotherEvent(), MyEvent(1), MyEvent(2)]

It should be possible by overriding transformEvents somehow and maybe using an extension of rxdart, but I wasn't able to get it right and would be glad if somebody could help me out. Thanks in advance!

1 Answer 1

0

Thanks to @narcodico, he posted this answer to my question on the flutter bloc github https://github.com/felangel/bloc/issues/2441

  @override
  Stream<Transition<SortEvent, SortState>> transformEvents(
    Stream<SortEvent> events,
    transitionFn,
  ) {
    return events
        .bufferTest((event) => event is BreakEvent)
        .flatMap<SortEvent>((bufferedEvents) async* {
      final sortedEvents = bufferedEvents.whereType<ValueEvent>().toList()
        ..sort((x, y) => x.value.compareTo(y.value));
      yield* Stream<SortEvent>.fromIterable([
        ...sortedEvents,
        ...bufferedEvents.whereType<BreakEvent>(),
      ]);
    }).asyncExpand(transitionFn);
  }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.