diff --git a/README.md b/README.md index bea94b2..ecf88dd 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,26 @@ internal class MyFeatureDialogSource : MutableStateSource } ``` +### SaveableMutableStateSource + +`SaveableMutableStateSource` is the same as `MutableStateSource` except it wraps its internal `State` in a +`rememberSaveable` call. + + +```kotlin +internal class MyCounterSource : SaveableMutableStateSource { + override val initial = 0 + + fun reset() { + update(0) + } + + fun increment() { + update(value + 1) + } +} +``` + ### DerivedStateSource `DerivedStateSource` is similar to `MutableStateSource`, but encapsulates the content of a `derivedStateOf` call: 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 index 1774855..afd4197 100644 --- a/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/SaveableMutableStateSource.kt +++ b/vice-sources/src/commonMain/kotlin/com/eygraber/vice/sources/SaveableMutableStateSource.kt @@ -3,12 +3,15 @@ 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.Saver 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 { +public abstract class SaveableMutableStateSource( + private val saver: Saver? = null, +) : ViceSource, State { private val state by lazy { mutableStateOf(initial) } @@ -24,5 +27,8 @@ public abstract class SaveableMutableStateSource : ViceSource, State { } @Composable - override fun currentState(): T = rememberSaveable { state }.value + override fun currentState(): T = when(saver) { + null -> rememberSaveable { state }.value + else -> rememberSaveable(stateSaver = saver) { state }.value + } }