Marcin Środa

    Marcin Środa

    2 years ago
    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

    2 years ago
    You could split up the dependency fetching and the actual rendering into 2 composables:
    @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
    Marcin Środa

    Marcin Środa

    2 years ago
    Yup, that’s one of the options - splitting core of the component.
    flosch

    flosch

    2 years ago
    You should probably not inject the ViewModel directly into your composables, but instead inject data and callbacks as mentioned above. That keeps everything lean