问题描述
当我们确切地知道我们有多少个具有确切类型的可观察对象并且我们想要压缩时,我们会这样做
When we know exactly how many observables we have with their exact types and we want to zip we do like this
Observable<String> data1 = Observable.just("one", "two", "three", "four", "five");
Observable<String> data2 = Observable.just("one", "two", "three", "four", "five");
Observable<String> data3 = Observable.just("one", "two", "three", "four", "five");
Observable.zip(data1, data2, data3, (a, b, c) -> a + b + c);
我们使用固定参数函数式接口,它接受 3 个参数......在这种情况下它可以正常工作.
we use fixed argument functional interface which takes 3 arguments... and it works ok in this case.
但是如果我们知道我们有 N 个 Observable
其中 T
是相同的类型,我们如何压缩它?消费者功能可以是需要 T...
but if we know that we have some N number of Observable<T>
where T
is the same type how do we zip it? consumer funtion can be something that takes T...
但我看不出有什么方法可以实现这一点...
but i dont see any way to implement this...
更新
我在这里尝试解决的实际问题是我有一些 Observable
并且我想 forkJoin 并在其中只选择一个 T
结束发射...
Practical problem i'm trying to solve here is that i have some number of Observable<T>
and i want to forkJoin those and chose only one T
in the end to emit...
想象几个 observables 发出 T
,我想把它和其他一些 observable 比较并只发出一个 ...
Imagine several observables emiting T
that i want to take and compare and emit only one with some other observable...
解决方案
正如回答中所说的,有一个带有可迭代对象和函数的 zip,示例代码如下所示
As said in answer there is a zip that takes an iterable and a function, sample code looks like this
Observable<String> data1 = Observable.just("one", "two", "three", "four", "five");
Observable<String> data2 = Observable.just("one", "two", "three", "four", "five");
Observable<String> data3 = Observable.just("one", "two", "three", "four", "five");
List<Observable<String>> iter = Arrays.asList(data1, data2, data3);
Observable.zip(iter, args1 -> args1).subscribe((arg)->{
for (Object o : arg) {
System.out.println(o);
}
});
这将产生
one
one
one
two
two
two
three
three
three
four
four
four
five
five
five
推荐答案
有一个采用 Iterable 的 zip 方法.这将允许使用 n 个 Observable.
There is a zip method which takes an Iterable. That would allow to use n Observables.
这篇关于带有可变参数的 RxJava zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!