1 /*
2  * 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.systemui.statusbar.notification.row.ui.viewbinder
18 
19 import android.widget.ViewFlipper
20 import androidx.lifecycle.lifecycleScope
21 import com.android.systemui.lifecycle.repeatWhenAttached
22 import com.android.systemui.statusbar.notification.row.ui.viewmodel.NotificationViewFlipperViewModel
23 import kotlinx.coroutines.DisposableHandle
24 import kotlinx.coroutines.coroutineScope
25 import kotlinx.coroutines.launch
26 
27 /** Binds a [NotificationViewFlipper] to its [view model][NotificationViewFlipperViewModel]. */
28 object NotificationViewFlipperBinder {
bindWhileAttachednull29     fun bindWhileAttached(
30         viewFlipper: ViewFlipper,
31         viewModel: NotificationViewFlipperViewModel,
32     ): DisposableHandle {
33         if (!viewFlipper.isAutoStart) {
34             // If the ViewFlipper is not set to AutoStart, the pause binding is meaningless
35             return DisposableHandle {}
36         }
37         return viewFlipper.repeatWhenAttached {
38             lifecycleScope.launch { bind(viewFlipper, viewModel) }
39         }
40     }
41 
bindnull42     suspend fun bind(
43         viewFlipper: ViewFlipper,
44         viewModel: NotificationViewFlipperViewModel,
45     ) = coroutineScope { launch { viewModel.isPaused.collect { viewFlipper.setPaused(it) } } }
46 
ViewFlippernull47     private fun ViewFlipper.setPaused(paused: Boolean) {
48         if (paused) {
49             stopFlipping()
50         } else if (isAutoStart) {
51             startFlipping()
52         }
53     }
54 }
55