Skip to content

Instantly share code, notes, and snippets.

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

Usage

            LiveData<Object> pollingLiveData = Transformations.switchMap(new PeriodicLiveData<Boolean>(appExecutors.scheduler(), 0, 5000, TimeUnit.MILLISECONDS) {
                @Override
                Boolean doWork() {
                    Log.d(this.getClass().getSimpleName(), "Tick!");
                    return true;
                }
            }, myActualLivedata());
package com.krillsson.android.example;
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) {
postValue(finishedWork);
}
};
public PeriodicLiveData(ScheduledExecutorService service, int initialDelay, int delay, TimeUnit timeUnit) {
scheduler = service;
this.delay = delay;
this.timeUnit = timeUnit;
this.initialDelay = initialDelay;
}
@Override
protected void onActive() {
scheduledFuture = scheduler.scheduleAtFixedRate(doWorkRunnable, initialDelay, delay, timeUnit);
}
abstract T doWork();
@Override
protected void onInactive() {
super.onInactive();
if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
scheduledFuture.cancel(false);
}
}
}
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.