为什么在没有postValue的情况下两次观察MutableLiveData触发器?

时间:2020-01-14 10:38:01

标签: android android-livedata

我想向Db添加文件路径,并且当DB中已经存在文件时,显示Toast消息。在ViewModel类中:

public void addFile(SharedFile file) {
    DefaultExecutorSupplier.getInstance().forBackgroundTasks()
            .execute(() -> {
                long result = fileRepository.insert(file);
                insertResult.postValue(result);
            }
    );
}

public MutableLiveData<Long> getInsertResult() {
    return insertResult;
}

和片段onViewCreated中:

    viewModel.getInsertResult().observe(getViewLifecycleOwner(), aLong -> {
        if (aLong == -1) {
            Toast.makeText(getContext(), getString(R.string.already_exist_file), Toast.LENGTH_LONG).show();
        }
    });

它可以工作,当我添加一个重复文件时,它会敬酒消息,但是问题是当我打开另一个片段并返回到当前片段时,它会再次敬酒消息。

1 个答案:

答案 0 :(得分:1)

这是因为(重新)订阅LiveData时,您始终会收到最后发出的值。参见here under Always up to date data。这里讨论了一些解决方法:Android LiveData prevent receive the last value on observe