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

Oussama Haff.

10/29/2020, 7:40 PM
Hello, is it really true that viewModel parameters are not supported for Composable preview or should I fire an issue about it ? This is the Composable that I’m trying to preview
Copy code
@Preview(group = "Themed Screens", showBackground = true, heightDp = 600, widthDp = 300)
@Composable
fun HomeScreenThemedPreview() {
    AppTheme {
        HomeScreen(viewModel = viewModel())
    }
}
g

Grigorii Yurkov

10/29/2020, 7:41 PM
I don't understand why this fact confused you
o

Oussama Haff.

10/29/2020, 7:52 PM
because the preview worked normally yesterday, but today and without any modifications, I got this message when I opened Android Studio, and the preview doesn’t work no more. Made me think that it might be a false negative !
l

Leland Richardson [G]

10/29/2020, 8:02 PM
I don’t have context on why it is/isn’t supported, but based on the error message it looks intentional. Feel free to file a bug to request it as a supported feature though
g

Grigorii Yurkov

10/29/2020, 8:07 PM
Hm, and this is strange for me that preview worked normally yesterday. I thought you cannot instantiate view model in preview, and this error is correct behaviour
a

Andrey Kulikov

10/29/2020, 9:08 PM
we didn't intent to support viewmodels creation from previews for purpose. usually viewmodels work with database or network. none of it will work in preview so there is no reason to support viewmodels in our opinion. try to destructure needed data from the viewmodel and have it as params on your function and then write preview for it as now you can correctly display it with fake data
(so I would be surprised if it worked for you at some point, it should always throw this exception)
a

allan.conda

10/30/2020, 12:57 AM
Hmm does that mean it would not be possible to preview the top-level function of the screens if its using ViewModels? That could mean the Previews in Navigator Editor might not be possible if that is not supported.
Currently for us it won’t be a problem as we hoist the state to the Fragment so our Screens are stateless. And I’m getting rid of Fragments soon to apply compose-navigation and I would have to move the ViewModels into the Screen function.
o

Oussama Haff.

10/30/2020, 8:21 PM
Thanks @Andrey Kulikov f& @Leland Richardson [G] for the response. By hoisting the value and the action up in the tree and passing them as composable args, the preview comes back. I surely don’t know why the preview worked even when using viewModels before ! but I’m certain it’s actually a good thing not to provide preview for Composables with anti-composing-pattern : )