1 /*
2  * Copyright (C) 2022 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 
18 package com.android.systemui.telephony.data.repository
19 
20 import android.telephony.Annotation
21 import android.telephony.TelephonyCallback
22 import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow
23 import com.android.systemui.dagger.SysUISingleton
24 import com.android.systemui.telephony.TelephonyListenerManager
25 import javax.inject.Inject
26 import kotlinx.coroutines.channels.awaitClose
27 import kotlinx.coroutines.flow.Flow
28 
29 /** Defines interface for classes that encapsulate _some_ telephony-related state. */
30 interface TelephonyRepository {
31     /** The state of the current call. */
32     @Annotation.CallState val callState: Flow<Int>
33 }
34 
35 /**
36  * NOTE: This repository tracks only telephony-related state regarding the default mobile
37  * subscription. `TelephonyListenerManager` does not create new instances of `TelephonyManager` on a
38  * per-subscription basis and thus will always be tracking telephony information regarding
39  * `SubscriptionManager.getDefaultSubscriptionId`. See `TelephonyManager` and `SubscriptionManager`
40  * for more documentation.
41  */
42 @SysUISingleton
43 class TelephonyRepositoryImpl
44 @Inject
45 constructor(
46     private val manager: TelephonyListenerManager,
47 ) : TelephonyRepository {
48     @Annotation.CallState
49     override val callState: Flow<Int> = conflatedCallbackFlow {
50         val listener = TelephonyCallback.CallStateListener { state -> trySend(state) }
51 
52         manager.addCallStateListener(listener)
53 
54         awaitClose { manager.removeCallStateListener(listener) }
55     }
56 }
57