Skip to content

Instantly share code, notes, and snippets.

@hrach
Created November 1, 2021 13:04
Show Gist options
  • Save hrach/4fe40eb76988676a3e7c2e393cd41c2f to your computer and use it in GitHub Desktop.
Save hrach/4fe40eb76988676a3e7c2e393cd41c2f to your computer and use it in GitHub Desktop.
savedMutableStateFlow
fun <T> ViewModel<*>.savedMutableStateFlow(
initialValue: T,
key: String? = null,
): ReadOnlyProperty<ViewModel<*>, MutableStateFlow<T>> {
var mutableStateFlow: MutableStateFlow<T>? = null
return ReadOnlyProperty { _, property ->
if (mutableStateFlow != null) {
return@ReadOnlyProperty mutableStateFlow!!
}
return@ReadOnlyProperty synchronized(this) {
if (mutableStateFlow != null) {
return@synchronized mutableStateFlow!!
}
val propertyName = key ?: property.name
val flowInitialValue = state.get<T>(propertyName) ?: initialValue
MutableStateFlow(flowInitialValue).also { flow ->
flow
.onEach { newValue -> state[propertyName] = newValue }
.launchIn(viewModelScope)
mutableStateFlow = flow
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment