• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.systemui.scene.ui.viewmodel
18 
19 import com.android.compose.animation.scene.UserAction
20 import com.android.compose.animation.scene.UserActionResult
21 import com.android.systemui.lifecycle.ExclusiveActivatable
22 import kotlinx.coroutines.awaitCancellation
23 import kotlinx.coroutines.flow.MutableStateFlow
24 import kotlinx.coroutines.flow.StateFlow
25 import kotlinx.coroutines.flow.asStateFlow
26 
27 /**
28  * Base class for view-models that need to keep a map of user actions up-to-date.
29  *
30  * Subclasses need only to override [hydrateActions], suspending forever if they need; they don't
31  * need to worry about resetting the value of [actions] when the view-model is deactivated/canceled,
32  * this base class takes care of it.
33  */
34 abstract class UserActionsViewModel : ExclusiveActivatable() {
35 
36     private val _actions = MutableStateFlow<Map<UserAction, UserActionResult>>(emptyMap())
37     /**
38      * [UserActionResult] by [UserAction] to be collected by the scene container to enable the right
39      * user input/gestures.
40      */
41     val actions: StateFlow<Map<UserAction, UserActionResult>> = _actions.asStateFlow()
42 
43     final override suspend fun onActivated(): Nothing {
44         try {
45             hydrateActions { state -> _actions.value = state }
46             awaitCancellation()
47         } finally {
48             _actions.value = emptyMap()
49         }
50     }
51 
52     /**
53      * Keeps the user actions up-to-date (AKA "hydrated").
54      *
55      * Subclasses should implement this `suspend fun` by running coroutine work and calling
56      * [setActions] each time the actions should be published/updated. The work can safely suspend
57      * forever; the base class will take care of canceling it as needed. There's no need to handle
58      * cancellation in this method.
59      *
60      * The base class will also take care of resetting the [actions] flow back to the default value
61      * when this happens.
62      */
63     protected abstract suspend fun hydrateActions(
64         setActions: (Map<UserAction, UserActionResult>) -> Unit,
65     )
66 }
67