我有一个AndroidViewModel
用在两个fragments
中,并且包含一个LiveData
对象,如下所示
public class CartViewModel<v extends CartCallback> extends BaseViewViewModel<v> {
private RoomDb roomDb;
private BaseApi api;
private AppExecutors executors;
private PrefsManger prefsManger;
private LiveData<List<LineEntity>> lines;
private LiveData<List<ImageEntity>> images;
private MutableLiveData<CartInfo> cartInfo;
private LiveData<Long> linesCount;
public CartViewModel(Application application, RoomDb roomDb, BaseApi api, AppExecutors executors, PrefsManger prefsManger) {
super(application);
this.roomDb = roomDb;
this.api = api;
this.executors = executors;
this.prefsManger = prefsManger;
lines = roomDb.lineDao().getAllLines();
}
public LiveData<List<LineEntity>> getLines() {
return lines;
}
public void saveOfflineLine(LineEntity entity) {
executors.diskIO().execute(() -> roomDb.lineDao().save(entity));
}
}
在这两个片段中,我都像这样启动视图模型
CartViewModel cartViewModel = ViewModelProviders.of(this, cartFactory).get(CartViewModel.class);
cartViewModel.attachView(this);
当我在onChange上观察到来自一个片段的liveData和来自另一片段的用户saveOfflineLine(entity)
时,不会触发
但是如果观察并保存相同的片段(表示视图模型中的实例相同)onChange
成功触发
答案 0 :(得分:1)
传递getActivity()
而不是this
,如下所示,以便在片段之间共享视图模型
CartViewModel cartViewModel = ViewModelProviders.of(getActivity(),cartFactory).get(CartViewModel.class);