Is there a library function to collect a StateFlow...
# compose
a
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
Want to submit a feature request?
a
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 :)