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.mode.ui.binder 18 19 import androidx.lifecycle.Lifecycle 20 import androidx.lifecycle.LifecycleOwner 21 import androidx.lifecycle.lifecycleScope 22 import androidx.lifecycle.repeatOnLifecycle 23 import com.android.customization.picker.mode.ui.viewmodel.DarkModeViewModel 24 import com.android.wallpaper.customization.ui.binder.SwitchColorBinder 25 import com.android.wallpaper.picker.customization.ui.viewmodel.ColorUpdateViewModel 26 import com.google.android.material.materialswitch.MaterialSwitch 27 import kotlinx.coroutines.launch 28 29 object DarkModeBinder { 30 fun bind( 31 darkModeToggle: MaterialSwitch, 32 viewModel: DarkModeViewModel, 33 colorUpdateViewModel: ColorUpdateViewModel, 34 shouldAnimateColor: () -> Boolean, 35 lifecycleOwner: LifecycleOwner, 36 ) { 37 lifecycleOwner.lifecycleScope.launch { 38 lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { 39 launch { viewModel.isEnabled.collect { darkModeToggle.isEnabled = it } } 40 launch { 41 var binding: SwitchColorBinder.Binding? = null 42 viewModel.previewingIsDarkMode.collect { 43 darkModeToggle.isChecked = it 44 binding?.destroy() 45 binding = 46 SwitchColorBinder.bind( 47 switch = darkModeToggle, 48 isChecked = it, 49 colorUpdateViewModel = colorUpdateViewModel, 50 shouldAnimateColor = shouldAnimateColor, 51 lifecycleOwner = lifecycleOwner, 52 ) 53 } 54 } 55 launch { 56 viewModel.toggleDarkMode.collect { 57 // Use onClickListener instead of onCheckedChangeListener to avoid the 58 // potential cycle of: system value changes->the toggle isChecked value is 59 // updated->the onCheckedChangeListener is called->the overriding value is 60 // set. The overriding value should not be set by the system, only by user. 61 darkModeToggle.setOnClickListener { _ -> it.invoke() } 62 } 63 } 64 } 65 } 66 } 67 } 68