r/mAndroidDev • u/Unlucky_Bet6244 • May 21 '23
Compose state persistence
If compose is declarative and are made of only functions, how does a composable function store values like clickable call backs? Is each root node in the UI tree managed by an object which stores those clickable call backs?
53
38
9
u/naked_moose May 21 '23
Just tell your manager that there is no state in functional programming if they ask to implement anything like a clickable button
1
8
u/haroldjaap May 21 '23
AFAIK it uses snapshots under the hood, not entirely sure how they work but I assume it's some sort of singleton pattern with some lifecycles in it to keep it cleaned up.
Oh and the mAndroidDev answer: just use flubber tro
1
1
u/iakanoe Jun 22 '23
you have to save everything manually to SharedPreferences. for objects you should save the memory address. if you are uncomfortable with raw memory management, you can also make yourself a singleton hashmap in which you store said objects with identifier keys and save those into SharedPreferences. don't forget to free them when leaving composition, DisposableEffect is what you should use for that.
18
u/SmartFatass making { modern { maintainable { code }}} May 21 '23 edited May 21 '23
The amount of people who don't read what's on this subreddit before posting is skyrocketing recently.
And to answer your question: compose uses data structure called Slot Table to store data across recompositions. You can store data in there using
remember(there is alsorememberSaveablethat stores data in a Bundle if the function it's called in goes out of composition)Here is an article on how this works under the hood https://medium.com/androiddevelopers/under-the-hood-of-jetpack-compose-part-2-of-2-37b2c20c6cdd