Created
January 14, 2020 11:29
-
-
Save mirmilad/a2bc50ac8bd583860c3d27112c0e8210 to your computer and use it in GitHub Desktop.
Simple DebouncedLiveData class for Android
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
import android.os.Handler; | |
import androidx.lifecycle.LiveData; | |
import androidx.lifecycle.MediatorLiveData; | |
import androidx.lifecycle.Observer; | |
public class DebouncedLiveData<T> extends MediatorLiveData<T> { | |
private LiveData<T> mSource; | |
private int mDuration; | |
private Runnable debounceRunnable = new Runnable() { | |
@Override | |
public void run() { | |
DebouncedLiveData.this.postValue(mSource.getValue()); | |
} | |
}; | |
private Handler handler = new Handler(); | |
public DebouncedLiveData(LiveData<T> source, int duration) { | |
this.mSource = source; | |
this.mDuration = duration; | |
this.addSource(mSource, new Observer<T>() { | |
@Override | |
public void onChanged(T t) { | |
handler.removeCallbacks(debounceRunnable); | |
handler.postDelayed(debounceRunnable, mDuration); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment