Issue
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!
Solution
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);
}
Answered By – Jeppi
Answer Checked By – Timothy Miller (FlutterFixes Admin)