Followup question to a discussion a while back: <h...
# compose
j
Followup question to a discussion a while back: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1614609620302500?thread_ts=1614345603.389700&amp;cid=CJLTWPH7S What would be the best way to collect a cold data source like this (scoped to the composable), but also keep a reference to it in the viewmodel? The viewmodel needs to keep a reference because we keep a bunch of
derivedStateOf
business logic inside it
a
do you have a more specific example?
j
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`
    }
}