1 /*
<lambda>null2  * 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.customization.picker.settings.data.repository
18 
19 import android.app.UiModeManager
20 import com.android.wallpaper.picker.di.modules.BackgroundDispatcher
21 import com.android.wallpaper.system.UiModeManagerWrapper
22 import java.util.concurrent.Executor
23 import javax.inject.Inject
24 import javax.inject.Singleton
25 import kotlinx.coroutines.CoroutineDispatcher
26 import kotlinx.coroutines.asExecutor
27 import kotlinx.coroutines.channels.awaitClose
28 import kotlinx.coroutines.flow.Flow
29 import kotlinx.coroutines.flow.callbackFlow
30 
31 @Singleton
32 class ColorContrastSectionRepository
33 @Inject
34 constructor(
35     uiModeManager: UiModeManagerWrapper,
36     @BackgroundDispatcher bgDispatcher: CoroutineDispatcher,
37 ) {
38     var contrast: Flow<Float> = callbackFlow {
39         val executor: Executor = bgDispatcher.asExecutor()
40         val listener =
41             UiModeManager.ContrastChangeListener { contrast ->
42                 // Emit the new contrast value whenever it changes
43                 trySend(contrast)
44             }
45 
46         // Emit the current contrast value immediately
47         uiModeManager.getContrast()?.let { currentContrast -> trySend(currentContrast) }
48 
49         uiModeManager.addContrastChangeListener(executor, listener)
50 
51         awaitClose {
52             // Unregister the listener when the flow collection is cancelled or no longer in use
53             uiModeManager.removeContrastChangeListener(listener)
54         }
55     }
56 }
57