One Off the Slack: @Preview and a ViewModel
Andreas Nilsson asked:
Is there a suggested way to create a preview if I use a ViewModel?
Create a preview with mocked data? I just saw the IDE said it didn’t support for viewmodels, so I was curious what the best practice will be
Google’s Jim Sproch replied:
Best practice is probably to avoid referencing AAC ViewModels in your composable functions. They are not platform-agnostic and almost always imply a strong coupling between your composable function and the rest of your application.
Instead, create an interface and only refer to the interface from your composable (this allows you to easily create an alternative implementation of the widget data that does not use AAC ViewModels), or read from the view model up at the top of your application and split it off into only the non-ViewModel data that your individual composables need.
When your composable does not behave well in Preview, that is almost always an indication your composable is not sufficiently isolated from the rest of the platform/application code.
Eric De Wildt offered:
Another alternative is to pass a data class with all of your state and callback functions in it.
And Google’s Sean McQuillan suggested:
I’d extend this to say any reference to a stateful final class in a composable is something to add carefully as it makes your composable inherently stateful, which can make testing and preview harder.
Roughly speaking, the idea is to push as much as possible towards the leaves of your code’s contribution to your composable hierarchy, and have those leaves be purely rendering logic, or as close as you can manage. For example, suppose that you are writing an app that has a screen that contains a scrollable list:
-
The row composables should not deal with state. That should all be passed in as parameters, both in terms of values and callbacks for events. Those rows should be able to be previewed easily, with some mock data supplied either as a
@Preview
parameter or as default parameters on the composable itself. -
The list composable might even be able to avoid state and be previewable in much the same way.
-
By the time you get to the screen composable, dealing with state starts to become unavoidable, because it has to live somewhere. That may mean that the screen is not able to be previewed readily, though.
Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!