r/androiddev • u/omarsahl • Aug 21 '26
Article Composition Over Inheritance in Android ViewModels
https://proandroiddev.com/composition-over-inheritance-in-android-viewmodels-51f3efba5f90
4
Upvotes
15
u/zerg_1111 Aug 21 '26 edited Aug 21 '26
How about just let each component have its own view model and have use cases for sharing view model logics instead of interfaces? Edit: typo
4
u/16cards Aug 21 '26
I have to sign up for Medium to read this?
1
u/dark_mode_everything Aug 21 '26
Each State holder holds the state for each shape, right? Doesn't that technically make them viewmodels as well?
1
u/kokeroulis Aug 22 '26
And this is the result of clean architecture... Put everything inside the viewmodel and then try to break it down with hacks and non elegant solutions.
You are just over complicating things with "magic architecture".
Your screen cares about things:
- LCE (Load Content Error)
- Overlays (tooltips, dialogs, bottom sheets, toasts etc)
- Actions that mutate the UI
- Navigation
- Analytics
The UI is just a list with different configuration for each screen, you don't have to make your life hard.
What I would do instead is the following:
LCE:
- Make your business logic to expose a Flow for your list
- When an action is submitted by the viewmodel to the business logic, I would make the Flow emit again with updated data, that way you have unidirectional data flow
- Then inside the business logic I would put a bunch of sealed intefaces to encapsulate the logic and the mapping
Overlays:
Use the observer pattern in order to emit different types of overlays from your business logic and pass a priority/strategy to resolve conflicts, when 2 or more overlays want to be displayed
Navigation:
Literally just a big nested sealed inteface that you map the result of it to a Compose Navigation key or a fragment or whatever
Analytics:
Same as navigation
TIP: If during the navigation or analytics, generating those objects becomes a bit convoluted because everything needs different parameters etc.
Then create a registar somewhere, for each heart, circle & hexagon. Then on the domain & UI layer just expose the classifiers for each item of the list.
Then once you click on that item for the navigation or to trigger tagging, just pass the id to the registar and the registar will give you a generic model that you can use.