How to pass variable parameters to Observer?

2019-07-13 20:12发布

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 ?

2条回答
迷人小祖宗
2楼-- · 2019-07-13 20:16

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.

查看更多
够拽才男人
3楼-- · 2019-07-13 20:18

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

Observable<Integer> mergedObservers = Observable.defer {
    firstAPI.getFirstInfo(userLat, userLong)
}.flatMap ...
查看更多
登录 后发表回答