Grouping [RxJava] [1,1,2,2,3,3,1,1] like [[1,1], [2,2], [3,3], [1,1]] To do

Summary

There was a case where I wanted to group the data taken as input by RxJava according to a certain rule and receive it. I don't want to put together non-contiguous values, so toMultiMap () and [groupBy ()](http://reactivex.io/ RxJava / javadoc / rx / Observable.html # groupBy) cannot be used.

Solution

It looks like this. Please do not miss the use of true and false unlike the title.

Judgment of equivalence should be possible with .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]
		 */
	}
}

At the timing when new data comes out (grouping ends) with .distinctUntilChanged () The data accumulated up to that point is output (.buffer () function).

Since both .buffer () and .distinctUntilChanged () read ʻObservable, it is set to Hot with .publish () `.

reference

http://stackoverflow.com/questions/31314345/rxjava-buffer-wind

Recommended Posts

Grouping [RxJava] [1,1,2,2,3,3,1,1] like [[1,1], [2,2], [3,3], [1,1]] To do
I want to do something like "cls" in Java
[Swift] I want to do something like C's sprinftf
What to do after Vagrant install
What to do when javax.batch.operations.JobStartException occurs
Reintroduction to Operators with RxJava Part 1
What to do if you don't like the code generated by swagger-codegen-cli