• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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 android.content.Context;
19 import android.os.Looper;
20 
21 import com.android.launcher3.MainThreadExecutor;
22 
23 import java.util.concurrent.ExecutionException;
24 
25 import androidx.annotation.VisibleForTesting;
26 
27 /**
28  * Utility class for defining singletons which are initiated on main thread.
29  */
30 public class MainThreadInitializedObject<T> {
31 
32     private final ObjectProvider<T> mProvider;
33     private T mValue;
34 
MainThreadInitializedObject(ObjectProvider<T> provider)35     public MainThreadInitializedObject(ObjectProvider<T> provider) {
36         mProvider = provider;
37     }
38 
get(Context context)39     public T get(Context context) {
40         if (mValue == null) {
41             if (Looper.myLooper() == Looper.getMainLooper()) {
42                 mValue = mProvider.get(context.getApplicationContext());
43             } else {
44                 try {
45                     return new MainThreadExecutor().submit(() -> get(context)).get();
46                 } catch (InterruptedException|ExecutionException e) {
47                     throw new RuntimeException(e);
48                 }
49             }
50         }
51         return mValue;
52     }
53 
getNoCreate()54     public T getNoCreate() {
55         return mValue;
56     }
57 
58     @VisibleForTesting
initializeForTesting(T value)59     public void initializeForTesting(T value) {
60         mValue = value;
61     }
62 
63     public interface ObjectProvider<T> {
64 
get(Context context)65         T get(Context context);
66     }
67 }
68