1 /*
2  * Copyright (C) 2023 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 
17 package com.android.launcher3.util
18 
19 import java.util.concurrent.Executor
20 import java.util.function.Consumer
21 import java.util.function.Supplier
22 
23 /** A [Runnable] that can be posted to a [Executor] that can be cancelled. */
24 class CancellableTask<T>
25 @JvmOverloads
26 constructor(
27     private val task: Supplier<T>,
28     // Executor where consumer needs to be executed on. Typically UI executor.
29     private val callbackExecutor: Executor,
30     // Consumer that needs to be accepted upon completion of the task. Typically work that needs to
31     // be done in UI thread after task completes.
32     private val callback: Consumer<T>,
33     // Callback to be executed on callbackExecutor at the end irrespective of the task being
34     // completed or cancelled
<lambda>null35     private val endRunnable: Runnable = Runnable {}
36 ) : Runnable {
37 
38     // flag to cancel the callback
39     var canceled = false
40         private set
41 
42     private var ended = false
43 
runnull44     override fun run() {
45         if (canceled) return
46         val value = task.get()
47         callbackExecutor.execute {
48             if (!canceled) {
49                 callback.accept(value)
50             }
51             onEnd()
52         }
53     }
54 
55     /**
56      * Cancel the [CancellableTask] if not scheduled. If [CancellableTask] has started execution at
57      * this time, we will try to cancel the callback if not executed yet.
58      */
cancelnull59     fun cancel() {
60         canceled = true
61         callbackExecutor.execute(this::onEnd)
62     }
63 
onEndnull64     private fun onEnd() {
65         if (!ended) {
66             ended = true
67             endRunnable.run()
68         }
69     }
70 }
71