在第二次实时数据之后观察实时数据

时间:2018-08-16 08:08:20

标签: android android-architecture-components android-livedata

我的视图模型 声明两个实时数据:

该场景将从存储库中获取两种方法,以便依赖于第一个实时数据的第二个实时数据输入参数获得数据

public class ProductViewModel extends AndroidViewModel {

private LiveData<DataWrapper<GetProductQuery.Product>> productLiveData;
private LiveData<DataWrapper<ArrayList<ProductList>>> vendorProductLiveData;


private ProductRepository repository ;

public ProductViewModel(@NonNull Application application) {
    super(application);
    repository = new ProductRepository();

}

public LiveData<DataWrapper<GetProductQuery.Product>> getProductLiveData(String productId) {
    productLiveData = repository.getProduct(productId);
    return productLiveData;
}

public LiveData<DataWrapper<ArrayList<ProductList>>> getVendorProductLiveData(int vendorId) {
    vendorProductLiveData = repository.getLimitProduct(vendorId);
    return vendorProductLiveData;
} }

在“活动”中,我要在第一个实时数据之后运行第二个实时数据:

viewModel.getVendorProductLiveData(Integer.parseInt(p.getId())).observe(getActivity(), arrayListDataWrapper -> {

                ArrayList<ProductList> pList = 
  arrayListDataWrapper.getData();
 });



viewModel.getProductLiveData(id).observe(this, productDataWrapper -> {
                p = productDataWrapper.getData();
});



                viewModel.getVendorProductLiveData(Integer.parseInt(p.getId())).observe(getActivity(), arrayListDataWrapper -> {
//do logic after get product

});

2 个答案:

答案 0 :(得分:0)

您应该在第一个通话中进行第二个通话。因此,当您收到第一个结果时,便可以使用它进行第二次呼叫

viewModel.getProductLiveData(id).observe(this, productDataWrapper -> {
          p = productDataWrapper.getData();
          viewModel.getVendorProductLiveData(Integer.parseInt(p.getId())).observe(getActivity(), arrayListDataWrapper -> {
                //do logic after get product

            }); 
 });

答案 1 :(得分:0)

您应该使用Transformations.switchMap()将前一个发射值作为参数,将第一个LiveData转换为第二个LiveData。然后,您可以观察经过转换的LiveData以获得最终结果。

相关问题