Architecture That Scales
State hoisting, ViewModel, StateFlow, navigation, Room, DataStore and the lifecycle. This is the part that separates a toy from an app.
State hoisting
Move state out of the composable that draws it. The piece becomes reusable, previewable and honest — and two parts of your screen can never disagree about what is true.
4.2ViewModel — state that outlives the screen
Turn the phone sideways and Dice Duel forgets the score. Here is exactly why that happens, and how a ViewModel keeps your state alive while Android throws the screen away and builds a new one.
4.3StateFlow and a single UI state object
Five loose values in a ViewModel will eventually contradict each other. Pack them into one object, publish it as a StateFlow, and the screen can never show a half-updated mixture again.
4.4Navigation between screens
Add a second screen, give it an address, carry a value to it, and make the phone's Back gesture do the obvious thing — without writing a single line of Back handling yourself.
4.5Room — a real database
Everything you have stored so far vanishes when the app closes. Room writes it to the phone properly, checks your queries at build time, and pushes fresh data to the screen the instant anything changes.
4.6DataStore — small settings
Not everything deserves a database. For a handful of settings — a length, a toggle, a chosen name — DataStore saves them safely, hands them back as a Flow, and never blocks the screen.
4.7The repository pattern
One class becomes the only part of your app that knows where data comes from. It is five lines long, it looks pointless the first time you see it, and it is the reason a rewrite later costs an afternoon instead of a week.
4.8Lifecycle, rotation and process death
There are three different ways your state can vanish, and each one is stopped by a different tool. Learn which is which, and how to make process death happen on demand so you can actually test it.