组合相同类型的'n'个可观察对象(RxJava) [英] Combining 'n' Observables of the same type (RxJava)
问题描述
我有一个代码流,可生成相同类型的Oberable的Iterable.然后,我将它们全部进行遍历,将它们组合在一起并以Observable的形式返回结果.目前,我正在使用带有FuncN的zip文件,这似乎太糟糕了,我想我已经错过了重点.这是一个使用Map的示例,这显然是胡说八道,但您明白了.
I have a code flow that generates an Iterable of Observables of the same type. I then go through them all, combining them and returning the result as an Observable. At the moment I'm using zip with a FuncN, which seems horrible and I think I've missed the point somewhere. Here's an example that uses a Map, it's obviously nonsense but you get the idea.
final ImmutableList.Builder<Map<String, Object>> observables =
ImmutableList.builder();
for (String key: keys) {
if (someTest(key)) {
observables.add(generateObservableMap(key));
}
}
return Observable.zip(observables.build(), data -> {
final Map<String, Object> result = Maps.newHashMap();
// THIS IS REALLY UGLY
for (Object d: data) {
for (Object e: ((Map) d).entrySet()) {
final Map.Entry entry = (Map.Entry) e;
final String key = (Model) entry.getKey();
final Object value = (AuthData) entry.getValue();
result.put(key, value);
}
}
return ImmutableMap.copyOf(result);
});
我敢肯定有更好的方法.
I'm sure there's a better way of doing this.
推荐答案
这实际上是关于Java集合的问题,而不是关于RxJava的问题.您可以使用putAll
将标记为REALLY UGLY
的部分变得更好一点:
This is actually more a question about Java Collections than about RxJava. The part that you labelled as REALLY UGLY
can be made a bit nicer using putAll
:
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> mergeMaps(Object... maps) {
final Map<K, V> result = new HashMap<K, V>();
for (Object map: maps) {
// unchecked <K,V> require @SuppressWarnings
result.putAll((Map<K,V>)map);
}
return result;
}
请注意,如果在多个地图中出现相同的键,则结果中只会包含该键的最后一个值.
Notice that if the same key occurs in several maps, only the last value for it will be in the result.
您可能想知道为什么我选择Object...
作为参数类型而不是Map<K,V>...
.原因是FuncN
将具有一个Object[]
,无法将其强制转换为Map<K,V>[]
,因为即使数组中的所有元素均为Map
类型,也会抛出一个ClassCastException
.
You may wonder why I chose Object...
as argument type instead of Map<K,V>...
. The reason is that FuncN
will have an Object[]
, which cannot be cast to a Map<K,V>[]
, because this would throw a ClassCastException
, even if all elements in the array are of type Map
.
现在,如果Iterable<Observable<Map<String, Object>>>
中有一些sampleObservables
,则可以按以下方式使用zip
和mergeMaps
:
Now if you have some sampleObservables
inside an Iterable<Observable<Map<String, Object>>>
, you can use zip
and mergeMaps
as follows:
return Observable.zip(sampleObservables, new FuncN<Map<String, Object>>() {
public Map<String, Object> call(Object... args) {
return mergeMaps(args);
}
});
这篇关于组合相同类型的'n'个可观察对象(RxJava)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!