Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian product in RxJava

Tags:

java

rx-java

Is it possible to get Cartesian product of two Observables in rxjava?

Something like this:

A -> 1,2,3
B -> a,b
A x B -> (1, a), (1, b), (2, a), (2, b), (3, a), (3, b)
like image 643
nmikhailov Avatar asked Mar 31 '14 14:03

nmikhailov


2 Answers

What you want is to produce, for one number, as pair as you have letters. So you can easily achive this using map and flatMap operator.

    Observable<Integer> number = Observable.from(Arrays.asList(1, 2, 3));
    Observable<String> letters = Observable.from(Arrays.asList("a", "b"));

    Observable<Pair> cartesian = number.flatMap((n) -> letters.map((l) -> new Pair(n, l)));
like image 65
dwursteisen Avatar answered Sep 22 '22 23:09

dwursteisen


Is "join" not what you looking for?

    Observable<Integer> a = Observable.fromArray(1, 2, 3);
    Observable<String>  b = Observable.fromArray("a", "b");

    Observable<?> left  = Observable.never();
    Observable<?> right = Observable.never();

    Observable<Pair<Integer, String>> pairs = a.join(b, (aa)->left, (bb)->right, (ai, bi)-> Pair.of(ai, bi));
like image 34
30thh Avatar answered Sep 22 '22 23:09

30thh