Created
September 19, 2021 17:18
-
-
Save fabioCollini/7e9d2499dd6f1020f57127b8e51adfcb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SavedStateHandleDelegate<T>( | |
private val savedStateHandle: SavedStateHandle, | |
private val key: String, | |
defaultValue: T, | |
) : ReadWriteProperty<Any, T> { | |
private val state: MutableState<T> | |
init { | |
val savedValue = savedStateHandle.get<T>(key) | |
state = mutableStateOf( | |
savedValue ?: defaultValue | |
) | |
} | |
override fun getValue(thisRef: Any, property: KProperty<*>) = state.value | |
override fun setValue(thisRef: Any, property: KProperty<*>, 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