I have viewmodel which I want to use in Parent com...
# compose
j
I have viewmodel which I want to use in Parent composable and then few levels down in child composable. What is best way in this case it sounds very wrong that i create dependencies and that I send viremodel instance all way down to the view that actually need on click to update viewmodel. Parent also based on viewmodel value change visibility of component but on button press child component update it. Any recommendation what is best practice?
r
You don’t have to pass the viewmodel all the way down. It suffices to pass lambdas to handle events.
Copy code
fun ChildComposable(
    onClickHandler: () -> Unit
)
j
So if i have parent A and child B -> C -> D -> i will all the way down send onClick handler right even if it is used only in D?
It sounds little bit weird that B and C have this dependency even if they do not use it.
r
Yes. A can take the viewModel as a parameter. All the children only pass handlers to each other.
Copy code
fun A(vm: YourViewModel){
   B(onClick = {vm.onClick()})
}
s
Yeah that sounds about right, you need the things to be passed down explicitly. Depending on what this A->B->C->D hierarchy looks like it could also be something that a a slot API may make simpler. Like how a Scaffold doesn’t take all of the functions etc. in the parameters and pass them down to the children, but let the entire child to be specified in one of the slots.
💯 1
👆 1
112 Views