groupBy
目录
1 groupBy的作用和使用场景
根据指定的条件将Publisher发送的数据分组,分组后的数据以key:value的形式被作为Flowable的发射项封装在GroupedFlowable中。
如果遇到需要将数据根据一定条件分类可以使用groupBy操作符
2 groupBy接口
<K> Flowable<GroupedFlowable<K,T>> | groupBy(Function<? super T,? extends K> keySelector) Groups the items emitted by a 根据指定的条件对发布者发出的项目进行分组,并将这些分组的项目作为GroupedFlowables发出。 |
<K> Flowable<GroupedFlowable<K,T>> | groupBy(Function<? super T,? extends K> keySelector, boolean delayError) Groups the items emitted by a 根据指定的条件对发布者发出的项目进行分组,并将这些分组的项目作为GroupedFlowables发出。 |
<K,V> Flowable<GroupedFlowable<K,V>> | groupBy(Function<? super T,? extends K> keySelector, Function<? super T,? extends V> valueSelector) Groups the items emitted by a 根据指定的条件对发布者发出的项目进行分组,并将这些分组的项目作为GroupedFlowables发出。 |
<K,V> Flowable<GroupedFlowable<K,V>> | groupBy(Function<? super T,? extends K> keySelector, Function<? super T,? extends V> valueSelector, boolean delayError) Groups the items emitted by a 根据指定的条件对发布者发出的项目进行分组,并将这些分组的项目作为GroupedFlowables发出。 |
<K,V> Flowable<GroupedFlowable<K,V>> | groupBy(Function<? super T,? extends K> keySelector, Function<? super T,? extends V> valueSelector, boolean delayError, int bufferSize) Groups the items emitted by a 根据指定的条件对发布者发出的项目进行分组,并将这些分组的项目作为GroupedFlowables发出。 |
<K,V> Flowable<GroupedFlowable<K,V>> | groupBy(Function<? super T,? extends K> keySelector, Function<? super T,? extends V> valueSelector, boolean delayError, int bufferSize, Function<? super Consumer<Object>,? extends Map<K,Object>> evictingMapFactory) Groups the items emitted by a 根据指定的条件对发布者发出的项目进行分组,并将这些分组的项目作为GroupedFlowables发出。 |
3 groupBy图解和说明
图解根据形状进行分组,很形象的说明搞了groupBy的作用
4 groupBy测试用例
@Test
public void groupBy() {
System.out.println("######groupBy#####");
Flowable.just(1, 20)
.groupBy(new Function<Integer, String>() {
@Override
public String apply(Integer integer) throws Exception {
return integer > 10 ? "1组" : "2组";
}
})
.subscribe(new Consumer<GroupedFlowable<String, Integer>>() {
@Override
public void accept(GroupedFlowable<String, Integer> groupedFlowable) throws Exception {
groupedFlowable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
String key = groupedFlowable.getKey();
System.out.println(key + ":" + String.valueOf(integer));
}
});
}
});
}
测试结果
######groupBy#####
2组:1
1组:20