Skip to content

Commit

Permalink
Add a Saver parameter to SaveableMutableStateSource (#213)
Browse files Browse the repository at this point in the history
eygraber authored Dec 11, 2024
1 parent 0566cbd commit 4dda63e
Showing 2 changed files with 28 additions and 2 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -200,6 +200,26 @@ internal class MyFeatureDialogSource : MutableStateSource<MyFeatureDialogState>
}
```

### SaveableMutableStateSource

`SaveableMutableStateSource` is the same as `MutableStateSource` except it wraps its internal `State` in a
`rememberSaveable` call.


```kotlin
internal class MyCounterSource : SaveableMutableStateSource<Int> {
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:
Original file line number Diff line number Diff line change
@@ -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<T> : ViceSource<T>, State<T> {
public abstract class SaveableMutableStateSource<T : Any>(
private val saver: Saver<T, out Any>? = null,
) : ViceSource<T>, State<T> {
private val state by lazy {
mutableStateOf(initial)
}
@@ -24,5 +27,8 @@ public abstract class SaveableMutableStateSource<T> : ViceSource<T>, State<T> {
}

@Composable
override fun currentState(): T = rememberSaveable { state }.value
override fun currentState(): T = when(saver) {
null -> rememberSaveable { state }.value
else -> rememberSaveable(stateSaver = saver) { state }.value
}
}

0 comments on commit 4dda63e

Please sign in to comment.