-->

How to pass variable parameters to Observer?

2019-07-13 20:02发布

问题:

I have two Observers that are merged with a flatMap. The first observer returns a value that is used when the second is called.

Observable<Integer> mergedObservers = firstAPI.getFirstInfo(userLat, userLong)
.flatMap(resultFirstObservable -> {
     try {
        return secondApi.getSecondInfo(resultFirstObservable.body().string(), "3") 
        .onErrorResumeNext(e -> {
            e.printStackTrace();
             return secondApi.getSecondInfo("defaultValue", "3");
          });
      } catch (IOException e) {
           e.printStackTrace();
           secondApi.getSecondInfo("defaultValue", "3") 
        .onErrorResumeNext(e -> {
            e.printStackTrace();
             return secondApi.getSecondInfo("defaultValue", "3");
          });
    });
}
}, (resultFirstObservable, resultSecondObservable) -> {
try {
    return transformToWhatINeed(resultSecondObservable.body().string());
} catch (IOException ex) {
    ex.printStackTrace();
    return transformToWhatINeed([]);
}
});

userLat and userLong are declared outside my method and are changed during the time the activity is open, but my Subscription takes into account only the first value of these. I would have expected that each time there's a new call, they will take the newest values.

What am I doing wrong ?

回答1:

If I understand you problem correctly using Observable.defer should solve problem

Observable<Integer> mergedObservers = Observable.defer {
    firstAPI.getFirstInfo(userLat, userLong)
}.flatMap ...


回答2:

Your method should be like:

 Observable.combineLatest(userLatObservable, userLongObervable, yourmergerfunction).flatmap( lat, long –> firstApi.get(lat, long))... Etc..

I think you problem is that how do you get the value of userLat amd userLong... Those values should first be converted to Observables to join them in the chain.