package be.digitalia.fosdem.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));
	}
}

@@ -681,56 +681,8 @@
 ) %7B%0A
-%09%09%09if (version == 0L) %7B%0A%09%09%09%09run();%0A%09%09%09%7D else %7B%0A%09
 %09%09%09f
@@ -731,17 +731,16 @@
 e();%0A%09%09%09
-%09
 if (now 
@@ -764,30 +764,21 @@
 %09%09%09%09
-%09handler.post(this
+update(now
 );%0A
-%09
 %09%09%09%7D
@@ -785,17 +785,16 @@
  else %7B%0A
-%09
 %09%09%09%09hand
@@ -838,14 +838,8 @@
 w);%0A
-%09%09%09%09%7D%0A
 %09%09%09%7D
@@ -933,36 +933,36 @@
 %0A%0A%09%09
-@Override%0A%09%09public void run(
+private void update(long now
 ) %7B%0A
@@ -1005,37 +1005,11 @@
 e = 
-SystemClock.elapsedRealtime()
+now
  + p
@@ -1072,16 +1072,97 @@
 is);%0A%09%09%7D
+%0A%0A%09%09@Override%0A%09%09public void run() %7B%0A%09%09%09update(SystemClock.elapsedRealtime());%0A%09%09%7D
 %0A%09%7D%0A%0A%09pu

Revert "Delay IntervalLiveData refresh to allow the previous result to be dispatched on active even when it's already expired"