关于样本,当评论说:
可以在公共方法中传递产品ID
这是指您可以创建一个公共setter方法。
自
productId
用于从数据库中获取LiveData,您应该使用
switchMap
,如您所述。这是因为
开关映射
允许您查找和更新
LiveData
指向,无需重新设置观察者。如果你没有使用
开关映射
,您需要告知您的活动以观察新查找的
LiveData
,并可能停止观察旧的
LiveData
对象
More description of this is included in the docs
.
还有一点需要注意的是,工厂在这里也很有用,因为你要通过或
注入
这个
DataRepository
通过构造函数的依赖关系。这是一种更好的将存储库引入类的方法,因为在测试时很容易模拟存储库。
考虑到这一点,如果您希望在工厂中执行此操作,那么您的代码可能类似于:
public class ProductViewModel extends AndroidViewModel {
private final LiveData<ProductEntity> mProduct;
private final LiveData<List<CommentEntity>> mComments;
private final MutableLiveData<Integer> mProductId = new MutableLiveData<>();
public ProductViewModel(@NonNull Application application) {
super(application);
// Have some way to get your repository, this is not great for testing...
Repository repository = ((BasicApp) application).getRepository();
mProduct = Transformations.switchMap(mProductId, id -> {
return repository.loadProduct(id);
}
mComments = Transformations.switchMap(mComments, id -> {
return repository.loadComments(id);
}
}
public void setProductId(int productId) {
mProductId.setValue(productId); // This will trigger both of those switchMap statements
}
}