<lambda>null1 package com.android.systemui.shared.condition
2 
3 import com.android.systemui.shared.condition.Condition.StartStrategy
4 import kotlinx.coroutines.CoroutineScope
5 import kotlinx.coroutines.Job
6 import kotlinx.coroutines.channels.awaitClose
7 import kotlinx.coroutines.flow.Flow
8 import kotlinx.coroutines.flow.callbackFlow
9 import kotlinx.coroutines.flow.distinctUntilChanged
10 import kotlinx.coroutines.launch
11 
12 /** Converts a boolean flow to a [Condition] object which can be used with a [Monitor] */
13 @JvmOverloads
14 fun Flow<Boolean>.toCondition(
15     scope: CoroutineScope,
16     @StartStrategy strategy: Int,
17     initialValue: Boolean? = null
18 ): Condition {
19     return object : Condition(scope, initialValue, false) {
20         var job: Job? = null
21 
22         override fun start() {
23             job = scope.launch { collect { updateCondition(it) } }
24         }
25 
26         override fun stop() {
27             job?.cancel()
28             job = null
29         }
30 
31         override fun getStartStrategy() = strategy
32     }
33 }
34 
35 /** Converts a [Condition] to a boolean flow */
Conditionnull36 fun Condition.toFlow(): Flow<Boolean?> {
37     return callbackFlow {
38             val callback =
39                 Condition.Callback { condition ->
40                     if (condition.isConditionSet) {
41                         trySend(condition.isConditionMet)
42                     } else {
43                         trySend(null)
44                     }
45                 }
46             addCallback(callback)
47             callback.onConditionChanged(this@toFlow)
48             awaitClose { removeCallback(callback) }
49         }
50         .distinctUntilChanged()
51 }
52