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

Jasmin Fajkic

07/15/2022, 9:26 AM
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

Roman Churkov

07/15/2022, 9:36 AM
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

Jasmin Fajkic

07/15/2022, 9:37 AM
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

Roman Churkov

07/15/2022, 9:41 AM
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

Stylianos Gakis

07/15/2022, 9:41 AM
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
76 Views