2017-05-20 8 views
1

私はRx用の新機能が新しく、知識を向上させるためにあなたの助けが必要です。だから、どんな助けもありがとう。複数のRxJava観測値を連結する方法

次のコードはうまく動作しますが、どのように改善できるかを知りたいと思います。単一観測値は2つあります(mSdkLocationProvider.lastKnownLocation()およびmPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude()))。 2番目に観察可能なのは最初の観察可能な結果に依存する。

私は、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は、一般に、2番目の操作が最初の操作の結果によって異なる場合に使用する演算子です。 flatMapはインライン加入者のように機能します。あなたが何か書くことができる上に、あなたの例:

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

あなたは上記の持っていた同じ加入者を使用することができますが、それはgetServiceTypeの結果を持っています。

関連する問題