LoginSignup
1
3

More than 5 years have passed since last update.

[RxJava] [1,1,2,2,3,3,1,1] を [[1,1], [2,2], [3,3], [1,1]] のようにグルーピングする

Last updated at Posted at 2017-07-24

あらまし

RxJavaで入力として取ったデータを一定のルールでグルーピングして受け取りたいケースがあった。
連続しない値はまとめたくないので、toMultiMap()groupBy()は使えない。

こんな感じになった。
題名と違ってtrue, false を使っているのはどうか見逃してほしい。

同値の判断は.distinctUntilChanged()でできるはず。

import rx.Observable;

public class RxJavaPlayground {
    public static void main(String[] args) {
        Observable.just(false, false, true, true, false, true, true)
        .publish(p -> {
            return p.buffer(() -> p.distinctUntilChanged());
        })
        .filter(x -> x.size() > 0)
        .subscribe((x) -> System.out.println(x));
        /*
         * =>
         * [false, false]
         * [true, true]
         * [false]
         * [true, true]
         */
    }
}

.distinctUntilChanged()で新しいデータが出る(グルーピングが終わる)タイミングで、
そこまで溜め込んだデータを出す(.buffer()の機能)ようにしている。

Observable.buffer().distinctUntilChanged()の両方が読むため、.publish()でHotにしている。

参考

1
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3