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

Ayomide

01/30/2021, 2:50 PM
Hi! I'm trying to model a sort of directory explorer UI with compose. I think I've got the underlying data structure right - however I want to do certain actions based on the name of the file that was opened. But I'm not sure how to get the "state" from a composable (like what it's current text is if it's a button) from outside the composable. For example in the screenshot below (haven't figured out how to tab them properly yet 😅 ) I have
File
composables that are created as "children" of a
FilePane
composable. Which means I have to hoist the same
onClick
callback to all of them. But how would I get a name like
Hello.java
from the
onClick
function that is given to all the buttons in the image when the
Hello.java
button is clicked? I feel like I am modelling this wrong, since composables should largely be stateless, except for the top level composable
j

jim

01/30/2021, 3:45 PM
Which means I have to hoist the same 
onClick
 callback to all of them.
This is the sentence which doesn't sound right to me. It's totally ok to have a different lambda for each child, you don't need to hoist the lambda creation up. The
onClick
lambda is not composable and so almost by definition it is stateless. When we say "stateless" we generally mean "no direct or indirect calls to `remember`". We mean that if you were to rerun/recreate the composable, or reuse the old composable, you wouldn't be able to tell the difference. An
onClick
lambda is not Composable and so it is almost by definition not going to be stateful because
remember
can only be called from a composable function. Recreating a non-stateful lambda on every composition is totally ok (and Compose may even do some optimizations to avoid unnecessary allocations, but you can safely ignore that detail). Therefore you don't need to worry about hoisting the `onClick`s up. Does the above make sense? I know, the data flow of functional composables can be a bit mind-bending the first time you see it, since it's so different from how data flow worked with the old Android View system and other imperative UI systems. Feel free to post some code snippets if you're still confused and we can help you refactor them.
👍 2
2
a

Ayomide

01/30/2021, 4:02 PM
Ah, thank you for the very helpful and detailed explanation! I see how the way I was looking at it was inaccurate. I'll try and refactor my code to reflect this 🙂
Yep, just thinking about it differently worked. Ended up hoisting the
ViewModel
that needed the text of whatever button was clicked to fetch that file. Made much more sense than hoisting one onClick
callback
for all of the buttons!
🎉 1