If I do something like the below, am I right in th...
# compose
a
If I do something like the below, am I right in thinking I cannot use preview it, because `ViewModel`s aren't supported in
@Preview
?
Copy code
@Composable
private fun TodoActivityScreen(todoViewModel: TodoViewModel) {
  ...
}
i
Your preview code can certainly construct an object to pass to your Composable, ViewModels aren't any different from any other object in that regard
🙌 1
Now if your ViewModel is constructed via Hilt/something else, you'd need to figure out how to construct all of those objects and on and on up the tree, which is where passing in just the specific state you need or an interface you can more easily mock that your ViewModel implements are all valid alternatives
👍 1
a
Copy code
java.lang.IllegalStateException: ViewModels creation is not supported in Preview
I get that when I try to do:
Copy code
todoViewModel = object : TodoViewModel() { }
i
That looks like the error when you call
viewModel()
. You sure you aren't calling that?
a
ViewModel()
as in the constructor? A capital
V
?
Because I'm definitely calling the ViewModel constructor. My ViewModel extends that, after all.
i
No, the composable method that constructs ViewModels and hooks it into the actual
ViewModelStoreOwner
https://developer.android.com/jetpack/compose/libraries#viewmodel
You can't call that or
hiltViewModel()
in something you want to Preview
a
No. I'm not calling that. I'll try to make a more concrete and contained example and post it. Give me a couple of minutes.
My mistake. It's nothing to do with /my/ view model. But there's a problem with
NavHost
and
@Preview
. It gives the above error about view models.
Copy code
@Composable
fun ExampleComp() {
  val controller = rememberNavController()
  NavHost(controller, "main") {
    composable("main") {
      Text("hi")
    }
  }
}
@Preview
@Composable
fun PreviewExampleComp() {
  ExampleComp()
}
i
Yes,
NavHost
uses
viewModel()
internally, that's expected.
Which is why the testing guide focuses on not using a `NavHost`/`NavController` in the components you want to preview at all: https://developer.android.com/jetpack/compose/navigation#testing
1
a
Ah, okay. I guess this error will crop up a lot. A warning when introducing Preview may help others to know this sooner. Thanks for you help, anyhow Ian.
i
Can you see the full stack trace? I would have expected that it would have included
NavHost
in it