LiveData没有观察到其他视图模型实例发生的更改吗?

时间:2018-12-26 15:03:37

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

我有一个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成功触发

1 个答案:

答案 0 :(得分:1)

传递getActivity()而不是this,如下所示,以便在片段之间共享视图模型

CartViewModel cartViewModel = ViewModelProviders.of(getActivity(),cartFactory).get(CartViewModel.class);