Skip to content

Instantly share code, notes, and snippets.

@mobiRic
Created August 17, 2020 08:51
Show Gist options
  • Save mobiRic/0842290a6220f7069c2b81b7fc5ce38a to your computer and use it in GitHub Desktop.
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.
/*
* 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;
}
}
@zkrige
Copy link

zkrige commented Aug 17, 2020

lgtm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment