RxJava中的groupBy,是將一個Observable分拆爲一些Observables集合,它們中的每一個發射原始Observable的一個 子序列,哪個數據項由哪一個Observable發射是由一個函數判定 的,這個函數給每一項指定一個Key,Key相同的數據會被同一個Observable發射。
在這裏插入圖片描述
先看個示例,就明白了:
ArrayList<Object> list = new ArrayList<Object>(); list.add(new Person()); list.add(new Person()); list.add(new Student()); list.add(new Student()); list.add(new Person()); list.add(new Student()); list.add(new Student());
Observable.from(list) .groupBy(new Func1<Object, Integer>() { @Override public Integer call(Object o) { if (o.getClass().getName().equals(Person.class.getName())) { return 1; } else { return 2; } } }) .subscribe(integerObjectGroupedObservable -> { int key = integerObjectGroupedObservable.getKey(); switch (key) { case 1: integerObjectGroupedObservable.subscribe(new Action1<Object>() { @Override public void call(Object o) { Log.e("groupBy", "call: 接收Person對象"); } }); break; case 2: integerObjectGroupedObservable.subscribe(new Action1<Object>() { @Override public void call(Object o) { Log.e("groupBy", "call: 接收Student對象"); } }); break; } });
結果:
call: 接收Person對象 call: 接收Person對象 call: 接收Student對象 call: 接收Student對象 call: 接收Person對象 call: 接收Student對象 call: 接收Student對象
在GroupBy的Func1()函數中按你的邏輯分組,並將每個信息對應的組的key標誌返回,如例子中我每個標誌都是Integer類型的,GroupBy會返回Observable的一個特殊子類GroupedObservable,這個特殊子類有個額外的方法getKey(),可用於獲得當前信息的組別。