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

Android 为什么在没有postValue的情况下观察两次MutableLiveData触发器?,android,android-livedata,Android,Android Livedata,我想将文件路径添加到Db,当Db中已经存在文件时,显示一条Toast消息。在ViewModel类中: public void addFile(SharedFile file) { DefaultExecutorSupplier.getInstance().forBackgroundTasks() .execute(() -> { long result = fileRepository.insert(file);

我想将文件路径添加到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;
}

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

这是因为当(重新)订阅LiveData时,您始终会收到最后发出的值。看见这里讨论了一些解决方法:

因为它的工作方式类似于行为继电器,而不是PublishRelay,因此您不应该期望它作为PublishRelay工作。AKA当您调用
observe
时,它将发出上次保留的值。这取决于如何在片段之间移动。。。您可以
在活动中初始化viewModel
,并通过
片段(…)
传递viewModel实例。那么,即使您在
相同的
liveData
    viewModel.getInsertResult().observe(getViewLifecycleOwner(), aLong -> {
        if (aLong == -1) {
            Toast.makeText(getContext(), getString(R.string.already_exist_file), Toast.LENGTH_LONG).show();
        }
    });