Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 98006509 authored by Alejandro Nijamkin's avatar Alejandro Nijamkin
Browse files

Kosmos utility for making Snapshot state unconfined.

I'm adding a usage in a downstream CL and am seeing some usages starting
to pop up as we gradually adopt the use of compose state in
non-composables as per go/sysui-arch:summer-24

Bug: 387321113
Test: verified with a unit test in a followup CL on this chain
Flag: TEST_ONLY
Change-Id: I5109b0f51adb64a61f1903080f47ec51e1297626
parent b97acd8e
Loading
Loading
Loading
Loading
+18 −0
Original line number Diff line number Diff line
package com.android.systemui.kosmos

import androidx.compose.runtime.snapshots.Snapshot
import com.android.systemui.SysuiTestCase
import com.android.systemui.coroutines.FlowValue
import com.android.systemui.coroutines.collectLastValue
@@ -57,6 +58,23 @@ var Kosmos.brightnessWarningToast: BrightnessWarningToast by
fun Kosmos.runTest(testBody: suspend Kosmos.() -> Unit) =
    testScope.runTest testBody@{ this@runTest.testBody() }

/**
 * Runs the given [Kosmos]-scoped test [block] in an environment where compose snapshot state is
 * settled eagerly. This is the compose equivalent to using an [UnconfinedTestDispatcher] or using
 * [runCurrent] a lot.
 *
 * Note that this shouldn't be needed or used in a compose test environment.
 */
fun Kosmos.runTestWithSnapshots(block: suspend Kosmos.() -> Unit) {
    val handle = Snapshot.registerGlobalWriteObserver { Snapshot.sendApplyNotifications() }

    try {
        testScope.runTest { block() }
    } finally {
        handle.dispose()
    }
}

fun Kosmos.runCurrent() = testScope.runCurrent()

fun <T> Kosmos.collectLastValue(flow: Flow<T>) = testScope.collectLastValue(flow)