Skip to content

Commit

Permalink
Add SaveableMutableStateSource (#210)
Browse files Browse the repository at this point in the history
  • Loading branch information
eygraber authored Dec 11, 2024
1 parent 01ce995 commit b559722
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions vice-sources/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ kotlin {

implementation(libs.compose.lifecycle)
api(compose.runtime)
api(compose.runtimeSaveable)

api(libs.kotlinx.coroutines.core)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<T> : ViceSource<T>, State<T> {
private val state by lazy {
mutableStateOf(initial)
}

public val updates: Flow<T> 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
}

0 comments on commit b559722

Please sign in to comment.