有没有更优雅的方式来执行和转换Map<K, Observable<V>>
至Map<K, V>
?
我发现了以下方法:
@Test
public void test() {
final ImmutableMap<String, Observable<Integer>> map = ImmutableMap.of(
"1", Observable.just(1),
"2", Observable.just(2),
"3", Observable.just(3)
);
Map<String, Integer> result = new HashMap<>(map.size());
final Integer execRes = map.entrySet()
.stream()
.map(entry -> {
entry.getValue().subscribe(res -> result.put(entry.getKey(), res));
return entry.getValue();
})
.reduce(Observable::concat).get().toBlocking().last();
Assert.assertTrue(execRes == 3);
Assert.assertTrue(1 == result.get("1"));
Assert.assertEquals("{1=1, 2=2, 3=3}", result.toString());
}
附:使用rxjava-1.1.7,Observable代码必须并行(同时)运行
最佳答案
这个怎么样?使用 Java 8 流:
Map<String, Integer> result = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toBlocking().first()));
同样使用 Rx:
Map<String, Integer> result = Observable.from(map.entrySet())
.toMap(Map.Entry::getKey, a -> a.getValue().toBlocking().first()).toBlocking().first();
关于java - 执行 Observables 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47057374/