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.kairos.internal
18
19 import com.android.systemui.kairos.util.Maybe
20 import com.android.systemui.kairos.util.just
21 import com.android.systemui.kairos.util.none
22 import java.util.concurrent.atomic.AtomicBoolean
23 import kotlinx.coroutines.CompletableDeferred
24 import kotlinx.coroutines.ExperimentalCoroutinesApi
25
26 /** Performs actions once, when the reactive component is first connected to the network. */
27 internal class Init<out A>(val name: String?, private val block: suspend InitScope.() -> A) {
28
29 /** Has the initialization logic been evaluated yet? */
30 private val initialized = AtomicBoolean()
31
32 /**
33 * Stores the result after initialization, as well as the id of the [Network] it's been
34 * initialized with.
35 */
36 private val cache = CompletableDeferred<Pair<Any, A>>()
37
connectnull38 suspend fun connect(evalScope: InitScope): A =
39 if (initialized.getAndSet(true)) {
40 // Read from cache
41 val (networkId, result) = cache.await()
42 check(networkId == evalScope.networkId) { "Network mismatch" }
43 result
44 } else {
45 // Write to cache
<lambda>null46 block(evalScope).also { cache.complete(evalScope.networkId to it) }
47 }
48
49 @OptIn(ExperimentalCoroutinesApi::class)
getUnsafenull50 fun getUnsafe(): Maybe<A> =
51 if (cache.isCompleted) {
52 just(cache.getCompleted().second)
53 } else {
54 none
55 }
56 }
57
initnull58 internal fun <A> init(name: String?, block: suspend InitScope.() -> A) = Init(name, block)
59
60 internal fun <A> constInit(name: String?, value: A) = init(name) { value }
61