再次发出先前在链中发出的对象

时间:2018-03-21 11:33:42

标签: java android rx-java rx-java2

如何再次发射先前在链中发出的对象。 例如,如果我们有以下场景,那么发出总和的最佳做法是什么?

Single.just(123)
    .zipWith(getConstant(), this::add)
    .map(sum -> getObject(sum))
    .flatMapCompletable(object -> doSomething(object))
    .andThen(Observable.just(sum)); //How to emit sum? 
                                    //What's the best option to do that without breaking the chain
                                    //What's the best practice for this situations?
                                    //Is this bad approach and does not follow Functional principles?

private Observable<Integer> getConstant() {
    return Observable.create(321);
}

private Integer add(Integer first, Integer second) {
    return first + second;
}

private Object getObject(Integer num) {
    return new Object();
}

private Completable doSomething(Object object) {
    return new Object();
}

1 个答案:

答案 0 :(得分:0)

使用flatMap

Single.just(123)
.zipWith(getConstant(), this::add)
.flatMap(sum -> 
     doSomething(getObject(sum))
     .andThen(Single.just(sum))
);