0

我想使用 Android 新架构组件在我的 Android 应用程序中显示产品列表。我有一个 Pojo 类Products,如下所示:

public class Products {

    private List<ProductDetails> products = null;
    private Integer onSaleCount;
    private Integer total;
    private Integer page;
.........................
}

网络服务返回带有分页的列表:

@GET("/products/")
Call<Products> getProducts(@Query("page") int page)

所以每次产品列表调用,我都会得到一组带有其他数据的产品列表。我已经定义了调用相同的方法ProductListRepository

public class ProductListRepository {
    @Inject
    ProductService mProductService;

    public Products getProductList(int pageNo) {
      .......................
      ..................
    }
}

但是我在设置 LiveData 时遇到了问题,ProductViewModel因为我想将 ListProductDetails与较旧的 List 合并,并更新其他变量的值,ProductsonSaleCount, pageNo

public class ProductListViewModel extends ViewModel {

private final ProductListRepository mProductListRepository;
private MediatorLiveData<Products> mProducts;

   public void getProductList(int pageNo) {

    Products products = mProductListRepository.getProductList(pageNo);
    if(products==null){
       mProducts.setValue(products);
    }else{
       // **How to add old List and new List and set it to LiveData**
    }
    return mProducts;
 }

}

谁能帮我?

4

1 回答 1

2

只是修改数据,mProducts可以是MutableLiveData<Products>,你的代码是这样的:

public void getProductList(int pageNo) {

  Products products = mProductListRepository.getProductList(pageNo);
  if (products == null) {
     // Nothing to do, no new data
  } else {
    Products oldProducts = mProducts.getValue();
    // merge oldProducts and products into newProducts, as you prefer
    mProducts.setValue(newProducts);
  }
}

MediatorLiveData旨在观察多个LiveData来源。

于 2017-07-21T12:14:57.197 回答