Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement