• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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.quickstep.util;
17 
18 import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
19 
20 import androidx.annotation.UiThread;
21 import androidx.annotation.WorkerThread;
22 
23 /**
24  * Utility class to executore a task on background and post the result on UI thread
25  */
26 public abstract class CancellableTask<T> implements Runnable {
27 
28     private boolean mCancelled = false;
29 
30     @Override
run()31     public final void run() {
32         if (mCancelled) {
33             return;
34         }
35         T result = getResultOnBg();
36         if (mCancelled) {
37             return;
38         }
39         MAIN_EXECUTOR.execute(() -> {
40             if (mCancelled) {
41                 return;
42             }
43             handleResult(result);
44         });
45     }
46 
47     /**
48      * Called on the worker thread to process the request. The return object is passed to
49      * {@link #handleResult(Object)}
50      */
51     @WorkerThread
getResultOnBg()52     public abstract T getResultOnBg();
53 
54     /**
55      * Called on the UI thread to handle the final result.
56      * @param result
57      */
58     @UiThread
handleResult(T result)59     public abstract void handleResult(T result);
60 
61     /**
62      * Cancels the request. If it is called before {@link #handleResult(Object)}, that method
63      * will not be called
64      */
cancel()65     public void cancel() {
66         mCancelled = true;
67     }
68 }
69