A method for using RxJava nested serial network requests

demand

When there is such a list of data that contains the information store + order to obtain a list of orders, order entity will contain a store ID, and the need to store the name and logo, this time on the need for nested serial network when the list display requested.

Key words

flatMap缓存RetrofitRxJava

Start work

(1) using a network interface is defined Retrofit

// RemoteService.java
// 请求订单信息
@POST("/order/v1/order_history")
Single<List<OrderResponse>> queryOrderList(@Body FetchOrderHistoryRequest request);
// 请求商店信息
@POST("/store/v1/store_query")
Single<StoreResponse> queryStore(@Body StoreQueryRequest request);

(2) using the management data DataManager

// DataManager.java
// 请求订单信息
public Single<List<OrderResponse>> queryOrderList(String status) {
    FetchOrderHistoryRequest request = new FetchOrderHistoryRequest();
    request.setStatus(status);
    return mRemoteService.queryOrderList(request);
}

// 请求商店信息,并缓存 5min,如果不作缓存可能导致多次重复请求同一数据
public static final int DEFAULT_CACHE_TIME_MILLIS = 5 * 60 * 1000; // 5min

public Single<StoreResponse> queryStore(String storeId) {
    String storeKey = PrefConstant.getStoreKey(storeId);
    String storeJson = mMemberPref.getString(storeKey, null);
    Single<StoreResponse> storeSingle;
    if (!TextUtils.isEmpty(storeJson)) {
        storeSingle = Single.just(Json.fromJson(storeJson, StoreResponse.class));
    } else {
        StoreQueryRequest request = new StoreQueryRequest();
        request.setId(storeId);
        storeSingle = mRemoteService.queryStore(request)
            .doOnSuccess(storeResponse -> mMemberPref.put(storeKey,
                                                          Json.toJson(
                                                              storeResponse),
                                                          DEFAULT_CACHE_TIME_MILLIS));
    }
    return storeSingle;
}

Note:

  1. mMemberPrefI wrote a use SharedPreferencesfor data caching class details View Pref.java

(3) several times FlatMap

dataManager.queryOrderList(status)
           .flatMapObservable((Function<List<OrderResponse>, ObservableSource<OrderResponse>>) Observable::fromIterable)
           .flatMap((Function<OrderResponse, ObservableSource<OrderHolder>>) orderResponse -> {
             OrderHolder orderHolder = new OrderHolder();
             orderHolder.setOrder(orderResponse);
             return dataManager.queryStore(orderResponse.getStoreId())
                               .flatMapObservable((Function<StoreResponse, ObservableSource<OrderHolder>>) storeResponse -> {
                                 orderHolder.setStore(storeResponse);
                                 return Observable.just(orderHolder);
                               });
           })
           .toList()
           .observeOn(AndroidSchedulers.mainThread())
           .subscribeOn(Schedulers.io())
           .subscribe(new SingleObserver<List<OrderHolder>>() {
             @Override
             public void onSubscribe(Disposable d) {
               disposable = d;
             }

             @Override
             public void onSuccess(List<OrderHolder> orderHolders) {
               if (orderHolders != null && !orderHolders.isEmpty()) {
                 getMvpView().showOrderList(orderHolders);
               } else {
                 getMvpView().showEmpty();
               }
             }

             @Override
             public void onError(Throwable e) {
               Timber.e(e);
               getMvpView().showError();
             }
           });
  }

Description:

  1. For the first time flatMapObservable, will be List<OrderResponse>converted ObservableSource<OrderResponse>;
  2. Second flatMap, the OrderResponseconverted ObservableSource<OrderHolder>;
  3. Third flatMapObservable, it will StoreResponsemerge into OrderHolder, and then converted ObservableSource<OrderHolder>.

Guess you like

Origin www.cnblogs.com/lshare/p/11333983.html