【发布时间】:2015-07-30 06:11:35
【问题描述】:
我和我的同事经常遇到挑战,我希望反应式编程能够解决它。不过,它可能需要我自己实现Operator 或Transformer。
我想获取任何Observable<T> 发出T 的项目,但我希望操作员将它们分组到T 的映射上,并将每个分组作为List<T> 发出,或者更好的是一些通用累加器,就像Java 8 流中的Collector。
但这是我认为groupBy() 无法做到的棘手部分。我想通过这个 Operator 获取两个 Observable,并假设发出的项目按该属性排序(传入的数据将从排序的 SQL 查询中发出并映射到 T 对象)。操作员将连续累积项目,直到属性更改,然后发出该组并继续下一个。这样我就可以从每个 Observable 中获取每组数据,压缩并处理这两个块,然后将它们扔掉并继续下一个。通过这种方式,我可以保持半缓冲状态并保持较低的内存使用率。
因此,如果我在 PARTITION_ID 上进行排序、分组和压缩,这在视觉上就是我想要完成的任务。
我这样做只是因为我可以有两个查询,每个查询都超过一百万条记录,并且我需要并排进行复杂的比较。我没有内存来一次从双方导入所有数据,但我可以将其范围缩小到每个排序的属性值并将其分成批次。每一批之后,GC 都会将其丢弃,操作员可以继续进行下一批。
这是我到目前为止的代码,但我有点不清楚如何进行,因为我不想在批处理完成之前发出任何东西。我该怎么做?
public final class SortedPartitioner<T,P,C,R> implements Transformer<T,R> {
private final Function<T,P> mappedPartitionProperty;
private final Supplier<C> acculatorSupplier;
private final BiConsumer<T,R> accumulator;
private final Function<C,R> finalResult;
private SortedPartitioner(Function<T, P> mappedPartitionProperty, Supplier<C> acculatorSupplier,
BiConsumer<T, R> accumulator, Function<C, R> finalResult) {
this.mappedPartitionProperty = mappedPartitionProperty;
this.acculatorSupplier = acculatorSupplier;
this.accumulator = accumulator;
this.finalResult = finalResult;
}
public static <T,P,C,R> SortedPartitioner<T,P,C,R> of(
Function<T,P> mappedPartitionProperty,
Supplier<C> accumulatorSupplier,
BiConsumer<T,R> accumulator,
Function<C,R> finalResult) {
return new SortedPartitioner<>(mappedPartitionProperty, accumulatorSupplier, accumulator, finalResult);
}
@Override
public Observable<R> call(Observable<T> t) {
return null;
}
}
【问题讨论】:
标签: java reactive-programming rx-java