0

I want to add file path to Db and when a file already exists in DB show a Toast message. In ViewModel class:

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

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

and in the Fragment onViewCreated:

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

It works and when I add a repetitive file it Toasts the message, but the problem is when I open another fragment and back to the current fragment it again Toasts message.

Amirhosein
  • 4,266
  • 4
  • 22
  • 35
  • Because it works like a BehaviorRelay and not a PublishRelay, therefore you should not expect it to work as a PublishRelay. AKA it will emit the last held value when you call `observe`. – EpicPandaForce Jan 14 '20 at 10:45
  • It depends on the way how to move between the fragments ... you can `initialize the viewModel` in the activity and pass on the viewmodel instance via `onAttachFragment(..)`. Then this scenario might not happen even if u call observe multiple times on the `same` `liveData` – Santanu Sur Jan 14 '20 at 10:57

1 Answers1

1

This is because when (re)subscribing to a LiveData you always receive the value that was emitted last. See here under Always up to date data. Some ways around this are discussed here: Android LiveData prevent receive the last value on observe

HDW
  • 308
  • 2
  • 14