Created
November 1, 2021 13:04
-
-
Save hrach/4fe40eb76988676a3e7c2e393cd41c2f to your computer and use it in GitHub Desktop.
savedMutableStateFlow
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
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