I want to subscribe to some data when my composable first appears on the screen (and have the subscription scoped to my composable). The composable has some heavy business logic associated with it, so all of the state is kept inside a ViewModel. The strategy in that thread shows how you can subscribe to a cold data source with
collectAsState
, but
collectAsState
is only available in composable functions so I’m not sure how I can reference it in my ViewModel:
Copy code
@Composable
fun ViewExercise(id: String) {
val viewExerciseViewModel: ViewExerciseViewModel = hiltNavGraphViewModel()
// I want to access this in the ViewModel
val exercise by remember { viewExerciseViewModel.exerciseFlow(id) }.collectAsState()
..
}
class ViewExerciseViewModel {
val equipment = derivedStateOf {
// some derived state of `exercise`
}
}