Flutter Bloc 使用 transformEvents 按事件值对事件队列进行排序
Flutter Bloc Sorting event queue by a value of the event with transformEvents
有没有一种简单的方法可以根据事件的值 class 对 flutter bloc 的事件队列进行排序?
例如。我有一个带有 int 属性 的 class MyEvent,事件队列如下所示:
[MyEvent(5), MyEvent(3), MyEvent(7), AnotherEvent(), MyEvent(2), MyEvent(1)]
我想对事件queue/stream进行改造,让int值最小的事件属性先执行-> [MyEvent(3), MyEvent(5), MyEvent(7), AnotherEvent(), MyEvent(1), MyEvent(2)]
应该可以通过覆盖 transformEvents
somehow and maybe using an extension of rxdart 来实现,但我无法做到正确,如果有人能帮助我,我会很高兴。提前致谢!
感谢@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);
}
有没有一种简单的方法可以根据事件的值 class 对 flutter bloc 的事件队列进行排序? 例如。我有一个带有 int 属性 的 class MyEvent,事件队列如下所示:
[MyEvent(5), MyEvent(3), MyEvent(7), AnotherEvent(), MyEvent(2), MyEvent(1)]
我想对事件queue/stream进行改造,让int值最小的事件属性先执行-> [MyEvent(3), MyEvent(5), MyEvent(7), AnotherEvent(), MyEvent(1), MyEvent(2)]
应该可以通过覆盖 transformEvents
somehow and maybe using an extension of rxdart 来实现,但我无法做到正确,如果有人能帮助我,我会很高兴。提前致谢!
感谢@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);
}