Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
class SavedStateHandleDelegate<T>(
private val savedStateHandle: SavedStateHandle,
private val key: String,
defaultValue: T,
initializer: (valueLoadedFromState: T?, setter: (T) -> Unit) -> Unit
) : ReadWriteProperty<Any, T> {
private val state: MutableState<T>
init {
val savedValue = savedStateHandle.get<T>(key)
state = mutableStateOf(
savedValue ?: defaultValue
initializer(savedValue, ::updateValue)
override fun getValue(thisRef: Any, property: KProperty<*>) = state.value
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
private fun updateValue(value: T) {
state.value = value
savedStateHandle.set(key, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment