0

I found that the LiveData returned by Dao will call its observer whenever my Fragment is created, even when the LiveData value is not changed. I have 2 Entity what have a one-to-one relation like this:

public class PetAndTracker {
@Embedded
public Tracker tracker;

@Relation(
        parentColumn = "serialNum",
        entityColumn = "trackerSerialNum"
)
public Pet pet;

public PetAndTracker() {
}

@Ignore
public PetAndTracker(Tracker tracker) {
    this.tracker = tracker;
}

@Ignore
public PetAndTracker(Pet pet) {
    this.pet = pet;
}

}

Dao method

@Transaction
@Query("SELECT * From Tracker")
LiveData<List<PetAndTracker>> getPetAndTrackerWithLiveData();

In my Fragment onCreate() method i call the LiveData method like:

    appDatabase.petDao()
            .getPetAndTrackerWithLiveData()
            .observe(this, new Observer<List<PetAndTracker>>() {
                @Override
                public void onChanged(List<PetAndTracker> list) {
        ...
                }
            });

onChanged return the whole PetAndTracker list that is in my database, but I only want that onChanged is trigger when the data really changed or I call an insert/update/delete methods.

developKinberg
  • 363
  • 4
  • 18
  • 1
    LiveData will emit whatever value it currently holds. From the documentation `If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.` https://developer.android.com/topic/libraries/architecture/livedata – tyczj Aug 14 '20 at 14:24
  • So I need to ignore the first callback and after this I can handle the new changes? – developKinberg Aug 14 '20 at 14:26
  • 2
    That's up to you, I personally would not use LiveData in your case and use Kotlin Flow since Flow does not re-emit like LiveData does https://medium.com/androiddevelopers/room-flow-273acffe5b57 – tyczj Aug 14 '20 at 14:32
  • Hm okay thanks for your advice, but I don't have any exp. in Kotlin, so this would be a future solution for me :) – developKinberg Aug 14 '20 at 14:49
  • 1
    As @tyczj suggest, a good solution for you is to use Flow, but a fast solution is to use implement a SingleLiveEvent. SingleLiveEvent only emits data to the current subscribers, if you recreate your view and observe this liveEvent, you won´t receive the data, only if the singleLiveEvent receive a new data. – Manuel Mato Aug 14 '20 at 15:53

0 Answers0