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



我想将文件路径添加到 Db,当数据库中已存在文件时,会显示一条 Toast 消息。在视图模型类中:

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();
}
});

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

这是因为当(重新(订阅LiveData时,您始终会收到最后发出的值。请参阅此处的始终最新数据。这里讨论了一些解决方法:Android LiveData 阻止在观察时接收最后一个值

最新更新