Created
August 17, 2020 08:51
-
-
Save mobiRic/0842290a6220f7069c2b81b7fc5ce38a to your computer and use it in GitHub Desktop.
LiveData class that counts how many times it has delivered updated values to Observers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (C) 2020 Glowworm Software | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
package mobi.glowworm.lib.lifecycle; | |
import androidx.annotation.NonNull; | |
import androidx.lifecycle.LiveData; | |
import androidx.lifecycle.MediatorLiveData; | |
/** | |
* {@link LiveData} wrapper that counts the number of times results have been delivered to observers. | |
* <p> | |
* i.e. how many times {@link androidx.lifecycle.Observer#onChanged(Object)} is called on the wrapped data. | |
*/ | |
public class CountingLiveData<T> extends MediatorLiveData<T> { | |
private int count = 0; | |
public CountingLiveData(@NonNull LiveData<T> source) { | |
super(); | |
addSource(source, changedValue -> { | |
count++; | |
setValue(changedValue); | |
}); | |
} | |
public int getCount() { | |
return count; | |
} | |
public boolean isFirstValue() { | |
return count == 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The use case behind this class is to know if an observed value is the first observation (possibly during initialisation of the UI), or a subsequent value change.
e.g. if waiting for GPS Location to be found, it might be useful to beep when initial location has been found, but remain silent on subsequent updates.