Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
LiveData extension that omits periodic ticks


            LiveData<Object> pollingLiveData = Transformations.switchMap(new PeriodicLiveData<Boolean>(appExecutors.scheduler(), 0, 5000, TimeUnit.MILLISECONDS) {
                Boolean doWork() {
                    Log.d(this.getClass().getSimpleName(), "Tick!");
                    return true;
            }, myActualLivedata());
import android.arch.lifecycle.LiveData;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public abstract class PeriodicLiveData<T> extends LiveData<T> {
private final int delay;
private final TimeUnit timeUnit;
private final int initialDelay;
private ScheduledFuture<?> scheduledFuture;
private ScheduledExecutorService scheduler;
private final Runnable doWorkRunnable = () -> {
T finishedWork = doWork();
if (finishedWork != null) {
public PeriodicLiveData(ScheduledExecutorService service, int initialDelay, int delay, TimeUnit timeUnit) {
scheduler = service;
this.delay = delay;
this.timeUnit = timeUnit;
this.initialDelay = initialDelay;
protected void onActive() {
scheduledFuture = scheduler.scheduleAtFixedRate(doWorkRunnable, initialDelay, delay, timeUnit);
abstract T doWork();
protected void onInactive() {
if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.