• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 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 static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
20 
21 import com.android.launcher3.dagger.LauncherAppSingleton;
22 
23 import java.util.ArrayList;
24 
25 import javax.inject.Inject;
26 
27 /**
28  * A tracker class for keeping track of Dagger created singletons.
29  * Dagger will take care of creating singletons. But we should take care of unregistering callbacks
30  * if at all registered during singleton construction.
31  * All singletons should be declared as SafeCloseable so that we can call close() method.
32  */
33 @LauncherAppSingleton
34 public class DaggerSingletonTracker implements SafeCloseable {
35 
36     private final ArrayList<SafeCloseable> mCloseables = new ArrayList<>();
37 
38     private boolean mClosed = false;
39 
40     @Inject
DaggerSingletonTracker()41     DaggerSingletonTracker() {
42     }
43 
44     /**
45      * Adds the SafeCloseable Singletons to the mLauncherAppSingletons list.
46      * This helps to track the singletons and close them appropriately.
47      * See {@link DaggerSingletonTracker#close()} and
48      * {@link SandboxContext#onDestroy()}
49      */
addCloseable(SafeCloseable closeable)50     public void addCloseable(SafeCloseable closeable) {
51         MAIN_EXECUTOR.execute(() -> {
52             if (mClosed) {
53                 closeable.close();
54             } else {
55                 mCloseables.add(closeable);
56             }
57         });
58     }
59 
60     @Override
close()61     public void close() {
62         mClosed = true;
63         // Destroy in reverse order
64         for (int i = mCloseables.size() - 1; i >= 0; i--) {
65             mCloseables.get(i).close();
66         }
67     }
68 }
69