【发布时间】:2018-05-05 07:10:45
【问题描述】:
说我有这个
Observable<A> getA() {
return Observable.just(new A());
}
Observable<C> getC() {
// ... some expensive call
return Observable.just(new C());
}
Observable<B> getB() {
return getA()
.map(a -> {
if (a.someCondition()) {
final B b = new B();
b.setSomeFields(...);
return b;
}
if (a.otherCondition()) {
final B b = new B();
b.setOtherFields(...);
return b;
}
final B b = new B(...);
b.setC(getC().toBlocking().single());
return b;
});
}
getC() 进行一些昂贵的调用(或有副作用)。我想进行此调用并仅在不满足a.someCondition() 或a. otherCondition() 时初始化B.c 字段,如上所述。
我将如何重写以摆脱.toBlocking()?
我想到的一种方法是压缩getA() 和getC():
Observable<B> getB() {
return Observable.zip(getA(), getC(), (a, c) -> Tuple.of(a, c))
.map(tuple -> {
final A a = tuple._1;
final C c = tuple._2;
if (a.someCondition()) {
final B b = new B();
b.setSomeFields(...);
return b;
}
if (a.otherCondition()) {
final B b = new B();
b.setOtherFields(...);
return b;
}
final B b = new B(...);
b.setC(c);
return b;
});
}
但这会一直拨打昂贵的电话。当有更复杂的条件或我有超过 2 个 Observables 需要压缩时,也很难阅读。
编辑:
@ESala 下面的回答有效,但有时从map 切换到flatMap 需要进行大量更改。下面的解决方案是否也有效?
Observable<B> getB() {
return getA()
.map(a -> {
if (a.someCondition()) {
final B b = new B();
b.setSomeFields(...);
return b;
}
if (a.otherCondition()) {
final B b = new B();
b.setOtherFields(...);
return b;
}
final B b = new B(...);
getC().forEach(c -> b.setC(c));
return b;
});
}
【问题讨论】:
标签: java functional-programming rx-java reactive-programming