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.intentresolver.shortcuts
18 
19 import android.app.prediction.AppPredictor
20 import android.app.prediction.AppTarget
21 import android.content.Context
22 import androidx.lifecycle.LifecycleOwner
23 import androidx.lifecycle.coroutineScope
24 import java.util.function.Consumer
25 import kotlinx.coroutines.CoroutineScope
26 import kotlinx.coroutines.awaitCancellation
27 import kotlinx.coroutines.launch
28 
29 /**
30  * A memory leak workaround for b/290971946. Drops the references to the actual [callback] when the
31  * [scope] is cancelled allowing it to be garbage-collected (and only leaking this instance).
32  */
33 class ScopedAppTargetListCallback(
34     scope: CoroutineScope?,
35     callback: (List<AppTarget>) -> Unit,
36 ) {
37 
38     @Volatile private var callbackRef: ((List<AppTarget>) -> Unit)? = callback
39 
40     constructor(
41         context: Context,
42         callback: (List<AppTarget>) -> Unit,
43     ) : this((context as? LifecycleOwner)?.lifecycle?.coroutineScope, callback)
44 
45     init {
<lambda>null46         scope?.launch { awaitCancellation() }?.invokeOnCompletion { callbackRef = null }
47     }
48 
notifyCallbacknull49     private fun notifyCallback(result: List<AppTarget>) {
50         callbackRef?.invoke(result)
51     }
52 
toConsumernull53     fun toConsumer(): Consumer<MutableList<AppTarget>?> =
54         Consumer<MutableList<AppTarget>?> { notifyCallback(it ?: emptyList()) }
55 
toAppPredictorCallbacknull56     fun toAppPredictorCallback(): AppPredictor.Callback =
57         AppPredictor.Callback { notifyCallback(it) }
58 }
59