# compose

Marcin Środa

08/11/2020, 8:17 AM
Do you expect to accept viewmodels in preview? Or is it disabled by design? I’m trying to create some kind of components which depends on states - in old approach I’ll use viewModel to handle lifecycle (like binding to service etc) and reuse some state. In compose I tried to pass viewModel as a parameter to composable - but I cannot use
now. Any ideas how to achive it? My goal is to create a standalone component based on custom library / framework with defined fetching messages or something 🙂

Joost Klitsie

08/11/2020, 8:32 AM
You could split up the dependency fetching and the actual rendering into 2 composables:
Copy code
fun myComposable() {
    val viewModel = // fetch viewModel
    val state = viewModel.viewState.collectAsState()

fun myActualComposable(state: MyViewState) {
    // compose stuff

fun previewComposable() {
    val viewState = MyViewState(
          // view state stuff like:
          text = "text",
          showError = false)
I am guessing that injection/getting viewmodel from the activity view model store is a tad difficult in preview mode as there is no actual running framework to deliver you the goods

Marcin Środa

08/11/2020, 8:49 AM
Yup, that’s one of the options - splitting core of the component.


08/11/2020, 10:44 AM
You should probably not inject the ViewModel directly into your composables, but instead inject data and callbacks as mentioned above. That keeps everything lean
☝️ 1