RxJava:在某些情况下从内部先执行另一个可观察的操作

时间:2018-11-28 05:33:56

标签: rx-java rx-java2 rx-android

我有以下

Observable<DATA> = getDataFromA();
Observable<DATA> = getDataFromB();

Observable<DATA> = getData();

public void getData() {
/*
   Here I would like to have the following in a single stream:
1. return getDataFromA();
2. after data from A is fetched: if (ConditionForB) then execute getDataFromB() observable. 
I would like to execute it separate but not merge with the stream from getDataFromA() because, this data is not to be provided back to the consumer. It is only to be executed and data stored somewhere. 
*/
}

Observable.concat()Observable.merge()将加入流,因此getDataFromB()的结果将被订户接收。 有没有一种方法可以在getDataFromB() observable之后执行getDataFromA(),但不向订户提供直接结果。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用Observable.flatMap()来实现该逻辑

getDataFromA()
    .flatMap(dataFromA -> {
        if (ConditionForB) {
            return getDataFromB()
                .map(dataFromB -> {
                     // TODO handle dataFromB
                     return dataFromA; // or merged result of dataFromA and dataFromB
                });
        } else {
            return Observable.just(dataFromA);
        }
    })