Is it possible to prevent LiveData receive the last value when start observing?
I am considering to use LiveData as events.
For example eve
I created a new Class that will hold my real data and a "special ID":
class LiveDataItem {
long mRealtimeNanos;
YOUR_PREVIOUS_LIVEDATA_TYPE mData;
LiveDataItem(YOUR_PREVIOUS_LIVEDATA_TYPE data, long realtimeNanos) {
this.mRealtimeNanos = realtimeNanos;
this.mData = data;
}
}
Then I created a new "global" variable:
final List mExcludedRealtimeNanos = new ArrayList<>;
At this point I choose to "set/postValue()" of my "LiveDataItem" type instead of the original "YOUR_PREVIOUS_LIVEDATA_TYPE" type via a new and custom "postValue()" method:
public void myPostValue(YOUR_PREVIOUS_LIVEDATA_TYPE data, boolean notifyWhenObserved) {
long cRealtimeNanos = SystemClock.realtimeNanos();
if (!notifyWhenObserved) mExcludedRealtimeNanos.add(cRealtimeNanos);
....postValue(new LiveDataItem(data, cRealtimeNanos));
}
Then I created a normal Observer that will receive all "Changed()" events and inside it I put a check about "RealtimeNanos":
public void onChanged(LiveDataItem myDataItem) {
boolean cFound = false;
for (Long cRealtimeNanos : mExcludedRealtimeNanos) {
if (cRealtimeNanos == myDataItem.mRealtimeNanos) {
cFound = true;
break;
}
}
//check if it was found --> NO: it means that I wish to get the notification
if (!cFound) mMyOnChangedCallback(myDataItem.mData)
}
Obliviously the "mMyOnChangedCallback()" method is a callback function that will be called whenever the original "onChanged()" event is raised BUT only if you set to notify it during data creation time.
You can choose to be notified again just by removing THAT RealtimeNanos from "mExcludedRealtimeNanos" and then attach a new Observer to that LiveData.
Few changes could improve this code but I wrote you what I remember of my old code (I'm currently away from my computer at this moment). For example we can decide to remove a value from "mExcludedRealtimeNanos" when a new data is posted using our custom postValue() method....