在RxJava / RxAndroid中的可观察对象之间传递响应

时间:2018-07-12 08:30:04

标签: java android rx-java rx-java2

我有此代码:

getLocationObservable() // ---> async operation that fetches the location. 
//  Once location is found(or failed to find) it sends it to this filter :
.filter(location -> {  // ---> I want to use this location in the the onNext in the end

     after finishing some calculation here, I either return 'true' and continue 
     to the next observable which is a Retrofit server call, or simply 
     return 'false' and quit.
})
.flatMap(location -> getRetrofitServerCallObservable( location )
     .subscribeOn(Schedulers.io())
     .observeOn(AndroidSchedulers.mainThread()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
     new Observer<MyCustomResponse>() {
          @Override
          public void onSubscribe(Disposable d) {
               _disposable = d;
          }
          @Override
          public void onNext(MyCustomResponse response) {
          // I want to be able to use the `location` object here
          }
          @Override
          public void onError(Throwable e) {

          }
          @Override
          public void onComplete() {

          }
     });

我希望能够在第二个可观察对象触发的“ onNext”中使用第3行(第一个可观察对象)中的location对象。 我无法解决..任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

代替

getRetrofitServerCallObservable( location )

您可以将结果映射为响应和位置的对(来自您喜欢的库):

getRetrofitServerCallObservable( location ).map(response -> Pair.create(location, response))

然后,在您的onNext中,您将收到Pair<Location,MyCustomResponse>个实例。

如果您不想使用Pair类,则可以使用Object[],但如果这样做,请不要告诉我:P

相关问题