我的视图模型声明了两个实时数据:
该场景从存储库获取两个方法,以便依赖于第一个实时数据的第二个实时数据输入参数获得数据
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
});发布于 2018-08-16 22:49:13
您应该使用Transformations.switchMap()将第一个LiveData转换为第二个LiveData,并使用前面发出的值作为参数。然后,您可以观察这个转换后的LiveData,以获得最终结果。
https://stackoverflow.com/questions/51872410
复制相似问题