How am I supposed to preview composable function which invokes
viewModel()
function?
m
Mikael Alfredsson
10/27/2020, 7:29 AM
you shouldn’t connect them in a “hard” way.
Let your composable take a lambda with the correct signature (same as the function you want to call) and in the preview you can send in a dummy expression, while in the real usage you send in a reference to your viewmodel function.
➕ 1
👍 1
Mikael Alfredsson
10/27/2020, 7:34 AM
Copy code
// function in Viewmodel
fun getText() :String {
return "RealText"
}
// usage in real code
SomeText(textFetcher = model::getText)
@Preview
@Composable
fun previewSomeText(){
SomeText(textFetcher = {"test text"})
}
@Composable
fun SomeText(textFetcher : ()-> String ){
Text(text = textFetcher())
}
g
Grigorii Yurkov
10/27/2020, 7:35 AM
Yeah, thank you, I got it
Grigorii Yurkov
10/27/2020, 7:42 AM
But, I think, you gave wrong example. Why do we need lambda here.
Copy code
// usage in real code
SomeText(textFetcher = viewModel.getText())
@Preview
@Composable
fun previewSomeText(){
SomeText("test text")
}
@Composable
fun SomeText(text: String){
Text(text = text)
}
We need lambda only for listeners
m
Mikael Alfredsson
10/27/2020, 8:11 AM
sorry, that was just an example function, it could be a function that returns different data depending on input, then you need the lambda (I should have added an parameter to the function)
j
Javier
10/27/2020, 8:17 AM
I had the same problem and I did previews for each state the screen can have instead of preview de entire screen composable which has the ViewModel