https://kotlinlang.org logo
#compose
Title
# compose
m

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
@Preview
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 🙂
j

Joost Klitsie

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

@Composable
fun myActualComposable(state: MyViewState) {
    // compose stuff
}

@Preview
@Composable
fun previewComposable() {
    val viewState = MyViewState(
          // view state stuff like:
          text = "text",
          showError = false)
    myActualComposable(viewState)
}
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
m

Marcin Środa

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

flosch

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