Skip to content

Instantly share code, notes, and snippets.

@cbeyls
Created April 27, 2019 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbeyls/fc5bb05e62cc3f857bcc825f91d67b5e to your computer and use it in GitHub Desktop.
Save cbeyls/fc5bb05e62cc3f857bcc825f91d67b5e to your computer and use it in GitHub Desktop.
A Factory providing utility LiveData instances
package be.digitalia.common.livedata;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import java.util.concurrent.TimeUnit;
public class LiveDataFactory {
static final Handler handler = new Handler(Looper.getMainLooper());
private LiveDataFactory() {
}
private static class IntervalLiveData extends LiveData<Long> implements Runnable {
private final long periodInMillis;
private long updateTime = 0L;
private long version = 0L;
IntervalLiveData(long periodInMillis) {
this.periodInMillis = periodInMillis;
}
@Override
protected void onActive() {
if (version == 0L) {
run();
} else {
final long now = SystemClock.elapsedRealtime();
if (now >= updateTime) {
handler.post(this);
} else {
handler.postDelayed(this, updateTime - now);
}
}
}
@Override
protected void onInactive() {
handler.removeCallbacks(this);
}
@Override
public void run() {
setValue(version++);
updateTime = SystemClock.elapsedRealtime() + periodInMillis;
handler.postDelayed(this, periodInMillis);
}
}
public static LiveData<Long> interval(long period, @NonNull TimeUnit unit) {
return new IntervalLiveData(unit.toMillis(period));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment