2017-05-20 33 views
1

我对Rx的东西超级新,需要你的帮助来提高我的知识。所以,任何帮助将不胜感激。如何连接多个RxJava observables,当下一个依赖于前一个?

以下代码正常工作,但是我想知道如何改进它。有两个单观测量(mSdkLocationProvider.lastKnownLocation()mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude()))。第二个可观察项取决于第一个可观察项的结果。

我知道有一些操作如zip,concat,concatMap,flatMap。我读了关于他们所有人,我现在很困惑:)

private void loadAvailableServiceTypes(final Booking booking) { 

    final Location[] currentLocation = new Location[1]; 
    mSdkLocationProvider.lastKnownLocation() 
      .subscribe(new Consumer<Location>() { 
       @Override 
       public void accept(Location location) throws Exception { 
        currentLocation[0] = location; 
       } 
      }, RxUtils.onErrorDefault()); 

    mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude()) 
      .subscribeOn(Schedulers.io()) 
      .observeOn(AndroidSchedulers.mainThread()) 
      .subscribe(new Consumer<ServiceTypeResponse>() { 
       @Override 
       public void accept(ServiceTypeResponse serviceTypeResponse) throws Exception { 
        onServiceTypesReceived(serviceTypeResponse.getServiceTypeList()); 
       } 
      }, new CancellationConsumer() { 
       @Override 
       public void accept(Exception e) throws Exception { 
        Logger.logCaughtException(TAG, e); 
       } 
      }); 
} 

所以,任何建议,将不胜感激。谢谢。

回答

3

flatMap一般是当你第二次操作取决于第一次的结果时使用的操作符。 flatMap就像内联用户一样工作。对于上面的示例,您可以编写如下所示的代码:

mSdkLocationProvider.lastKnownLocation() 
    .flatMap(currentLocation -> { 
     mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude()) 
    }) 
    .subscribeOn(Schedulers.io()) 
    .observeOn(AndroidSchedulers.mainThread()) 
    .subscribe(...) 

您可以使用与上面相同的订阅者,它将得到getServiceType的结果。

相关问题