Is there a library function to collect a StateFlow to State without being @Composable?
It is, I think, pretty trivial to do myself, but I can imagine it is a pretty common pattern in something like a ViewModel?
Copy code
class AppViewModel(val someExternalStateFlow: StateFlow<Something>, val scope: CoroutineScope) {
private var _state = mutableStateOf(someExternalStateFlow.current)
val state: Something by _state
init {
someExternalStateFlow.onEach { _state.value = it }.launchIn(scope)
}
}
Something like this:
Copy code
fun <T> StateFlow<T>.collectAsState(scope: CoroutineScope): State<T> {
val state = mutableStateOf(this.value)
this.onEach { update ->
state.value = update
}.launchIn(scope)
return state
}
👀 1
z
Zach Klippenstein (he/him) [MOD]
06/06/2022, 12:46 AM
Want to submit a feature request?
a
Arjan van Wieringen
06/06/2022, 6:03 AM
A PR in Compose you mean or something? Sure.
Since the compose libs are of so high quality, and this missing, was thinking I was convinced I was doing something wrong :)