From 449c27728a16f6042a60fe4ac49d698d35334e34 Mon Sep 17 00:00:00 2001 From: Eliezer Graber Date: Tue, 10 Dec 2024 19:52:44 -0500 Subject: [PATCH] Add SaveableMutableStateSource --- vice-sources/build.gradle.kts | 1 + .../sources/SaveableMutableStateSource.kt | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/SaveableMutableStateSource.kt diff --git a/vice-sources/build.gradle.kts b/vice-sources/build.gradle.kts index d3be241..6ba534a 100644 --- a/vice-sources/build.gradle.kts +++ b/vice-sources/build.gradle.kts @@ -22,6 +22,7 @@ kotlin { implementation(libs.compose.lifecycle) api(compose.runtime) + api(compose.runtimeSaveable) api(libs.kotlinx.coroutines.core) } diff --git a/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/SaveableMutableStateSource.kt b/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/SaveableMutableStateSource.kt new file mode 100644 index 0000000..1774855 --- /dev/null +++ b/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/SaveableMutableStateSource.kt @@ -0,0 +1,28 @@ +package com.eygraber.vice.sources + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.snapshotFlow +import com.eygraber.vice.ViceSource +import kotlinx.coroutines.flow.Flow + +public abstract class SaveableMutableStateSource : ViceSource, State { + private val state by lazy { + mutableStateOf(initial) + } + + public val updates: Flow get() = snapshotFlow { state.value } + + override val value: T get() = state.value + + protected abstract val initial: T + + protected fun update(value: T) { + state.value = value + } + + @Composable + override fun currentState(): T = rememberSaveable { state }.value +}