RxJava中的n元笛卡尔积 [英] n-ary Cartesian product inRxJava
本文介绍了RxJava中的n元笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在我拥有一个Observable<Observable<Integer>
,如何将其转移到包含n元笛卡尔积的Observable<int[]>
中?
Now I hold an Observable<Observable<Integer>
, how can I transfer it into Observable<int[]>
that contains the n-ary Cartesian product?
例如:
Observable<Observable<Integer> ob = Observable.just(
Observable.just(0,1),
Observable.just(2,3),
Observable.just(4,5)
);
ob...... -> (0,2,4), (0,3,4), (0,2,5), (0,3,5), (1,2,4), (1,3,4), (1,2,5), (1,3,5)
推荐答案
首先,您需要固定数量的输入Observable
.其次,不需要阻塞,但是可能需要缓存,因为第二,第三等Observable
需要多次使用.
First of all, you need a fixed number of input Observable
s. Second, there is no need for blocking but there is likely the need for caching because the 2nd, 3rd etc Observable
s need to be consumed multiple times.
import java.util.*;
import io.reactivex.Observable;
public class Cartesian {
static Observable<int[]> cartesian(Observable<Observable<Integer>> sources) {
return sources.toList().flatMapObservable(list -> cartesian(list));
}
static Observable<int[]> cartesian(List<Observable<Integer>> sources) {
if (sources.size() == 0) {
return Observable.<int[]>empty();
}
Observable<int[]> main = sources.get(0).map(v -> new int[] { v });
for (int i = 1; i < sources.size(); i++) {
int j = i;
Observable<Integer> o = sources.get(i).cache();
main = main.flatMap(v -> {
return o.map(w -> {
int[] arr = Arrays.copyOf(v, j + 1);
arr[j] = w;
return arr;
});
});
}
return main;
}
public static void main(String[] args) {
cartesian(Observable.just(
Observable.just(0, 1),
Observable.just(2, 3),
Observable.just(4, 5)
))
.subscribe(v -> System.out.println(Arrays.toString(v)));
}
}
这篇关于RxJava中的n元笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文