1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.launcher3.util;
17 
18 import java.util.ArrayList;
19 
20 /**
21  * Utility class to hold a list of runnable
22  */
23 public class RunnableList {
24 
25     private ArrayList<Runnable> mList = null;
26     private boolean mDestroyed = false;
27 
28     /** Adds a runnable to this list */
add(Runnable runnable)29     public void add(Runnable runnable) {
30         if (runnable == null) {
31             return;
32         }
33         if (mDestroyed) {
34             runnable.run();
35             return;
36         }
37         if (mList == null) {
38             mList = new ArrayList<>();
39         }
40         mList.add(runnable);
41     }
42 
43     /** Removes a previously added runnable */
remove(Runnable runnable)44     public void remove(Runnable runnable) {
45         if (mList != null) {
46             mList.remove(runnable);
47         }
48     }
49 
50     /**
51      * Destroys the list, executing any pending callbacks. All new callbacks are
52      * immediately executed
53      */
executeAllAndDestroy()54     public void executeAllAndDestroy() {
55         mDestroyed = true;
56         executeAllAndClear();
57     }
58 
59     /**
60      * Executes all previously added runnable and clears the list
61      */
executeAllAndClear()62     public void executeAllAndClear() {
63         if (mList != null) {
64             ArrayList<Runnable> list = mList;
65             mList = null;
66             int count = list.size();
67             for (int i = 0; i < count; i++) {
68                 list.get(i).run();
69             }
70         }
71     }
72 
73     /**
74      * Returns true if the list has been destroyed
75      */
isDestroyed()76     public boolean isDestroyed() {
77         return mDestroyed;
78     }
79 }
80