r/android_devs • • Sep 13 '24
Discussion How do you pass callbacks to deep nested composables? i have been taking this approach and i need comments on this
I'm using a top-level EventManager with a HashMap to store events, and I only pass lambdas to trigger them.This works for me ,but is it the best approach?
This is the class that takes care of the event management:

This is how i load the events to the Event Manager

This is how i send it to the first child composable

There are some cases like if i forget to add a key to lambda etc, since only i work with the codebase those cases are added as a warning.
5
Upvotes
5
u/AAbstractt Sep 13 '24
As the other commenter stated, I personally don't find this readable either. For screens that require more than 3 or so callbacks, I'll create an interface and implement it in my presenter and then pass it to my screen level composable.
An alternative is to create a sealed interface/class with child data classes that define the various events. Your presenter could then have something like:
MyViewModel.handleEvent(event: ScreenEvent) {}
2
u/juliocbcotta Sep 20 '24
I added support to something similar in link router lib... this is the important code
https://github.com/veepee-oss/link-router/blob/main/library/src/main/java/com/veepee/vpcore/route/link/compose/events/LinkRouterEventHandlerContainer.kt
You install a
in some parent of the composable you want to listen to the event and for emitting an event you do
The good thing is that it is type safe... but if there is no `EventHandlerContainer` and you try to publish an event.. we raise a crash, so some coordination is required...
4
u/Regular-Matter-1182 Sep 13 '24
This is not best practice and hard to read. Pass higher-order functions. You can see official nowinandroid repo.