Does anyone have recommendations for hoisting func...
# compose
c
Does anyone have recommendations for hoisting functions through many layers of composables? For example, when the function is defined in a screen-level viewmodel, and is called by a button click on dialog thats opened by button on a card, thats in a list, that's in a scaffold, etc., etc... I've been working on a compose app for a few months now. As the app has grown, I'm started to come upon some new quality of life annoyances. One of them is having to cary simple
onSuchAndSuchClick: () -> Unit
parameters through many nested composables. One alternative is to pass the viewmodel itself further down, though this has it's drawbacks too. So what are other folks doing in your apps?
r
Curious about this as well. So far I have either passed the viewModel as a param or just kept the UI design overly nested in a single file.
c
If you are concerned about passing along several lambdas, you could consider a single
actionHandler: (Action) -> Unit
instead (where
Action
is a sealed hierarchy). See this thread for more discussions around the pros and cons.
Another option might be to use slots (i.e, Composable lambdas). Here's an article about it: https://chrisbanes.me/posts/slotting-in-with-compose-ui/
❤️ 1
I strongly recommend against passing down the ViewModel. The VM should never leave the top level Screen Composable. It makes previewing, testing or reusing the lower level composables harder.
👍 1
c
thanks @curioustechizen - both very useful options that hadn't occurred to me! I found another article that especially helped me understand how slots would save a few layers of passing lambdas... i think it's on your yours haha https://kiranrao.in/blog/2021/12/03/jetpack-compose-slots/
🙇🏽 1
❤️ 1
t
Thanks for these articles (about slotting). It would be interesting if it were easy to somehow whip up some script that would analyze @Composable functions that are simply passing parameters along to other ones. If the parent function is making no read access to the parameter, just passing it along to the child composables, then that would seem like candidates for this type of slotification.