I need to run a sequence of runnables on the main (ui) thread with a given delay between them indefinitely until signalled to stop. Code:
public class UiLoop {
private Handler h;
private AtomicBoolean breakLoop;
@UiThread
public UiLoop() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new RuntimeException("Not called on ui thread!");
}
h = new Handler();
breakLoop = new AtomicBoolean(false);
}
/**
* Break out of the loop on the next iteration.
*/
public void breakLoop() {
this.breakLoop.set(true);
}
/**
* @param workers A Deque of runnables to execute sequentially.
* @param delay The delay between executing the runnables. This is excluding the time it
* takes for the runnable to complete.
*/
@UiThread
public void loop(Deque<Runnable> workers, int delay) {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new RuntimeException("Not called on ui thread!");
}
if (workers.isEmpty()) return;
if (breakLoop.get()) return;
final Runnable first = workers.removeFirst();
h.post(first);
workers.addLast(first);
h.postDelayed(() -> loop(workers, delay), delay);
}
}
Is the above code OK?
PS: I am using retrolambda to convert Anonymous Inner Classes to lambda functions.