Share
Compose Beyond the UI: Architecting Reactive State Machines at Scale
Jetpack Compose has redefined how we build UIs... but most apps still fall back on ViewModels and scattered logic that don’t scale well. As complexity grows, this leads to inconsistent screens, hard-to-reproduce bugs, and duplicated code. In this talk, we’ll look at how to move beyond MVVM/MVI into a reactive state machine model that fits Compose’s declarative style. You’ll learn how to design clean state contracts, coordinate transitions across navigation stacks and dialogs, and handle side effects like navigation or snackbars in a predictable way. We’ll also cover async patterns, modularizing domain state, debugging techniques for tracking state evolution, and testing UIs with simulated states and time-based transitions. By the end, you’ll leave with practical techniques to make Compose apps more scalable, debuggable, and easier to maintain.
Adit Lal
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
119 slides
-
Patterns for predictable, testable, scalable UI state Compose Beyond the
UI: Architecting Reactive State Machines at Scale Adit Lal GDE Android -
Wh a t bre a ks a t sc a
le Why it bre a ks? Build ment a l models How to f ix it I d e n t i f y P a t t e rns So l u t ions Compose Beyond the UI: Architecting Reactive State Machines at Scale Patterns for predictable, testable, scalable UI state -
- Common bugs th a t seem r a ndom
- Symptoms vs root c a uses - The "it works on my m a chine" problem I d e n t i f y P e So t -
- St a te t a xonomy (ephemer a l
→ screen → dom a in) - Boole a n explosion → st a te m a chines - T a ngled tr a nsitions → pure functions y P a t t e rns So t -
- St a - Boole a - T a y
P e So l u t ions - Se a led interf a ces for impossible st a tes - Tr a nsitionResult for e ff ects a s outputs - Testing without mocks -
Three Bugs Everyone Has - Sn a ckb a r
shows a g a in a fter rot a tion -
Three Bugs Everyone Has - Sn a ckb a r
shows a g a in a fter rot a tion - Button Fires twice on f a st t a p -
Three Bugs Everyone Has - Sn a ckb a r
shows a g a in a fter rot a tion - Button Fires twice on f a st t a p - Screen shows st a le d a t a a fter b a ck n a vig a tion -
Three Bugs Everyone Has - Sn a - Button Fires
twice on f a - Screen shows st a These Aren't Compose Bugs These are State bugs -
Three Bugs Everyone Has - Sn a - Button Fires
twice on f a - Screen shows st a These Aren't Compose Bugs These are State bugs The Three Layers of State -
The Three Layers of State Ephemeral remember { } Screen
ViewModel Domain Repository -
Ephemeral remember { } Screen ViewModel Domain Repository Form Screen
The Three Layers of State Where does e a ch st a te live? Wrong Layer == Bugs -
Ephemeral remember { } Screen ViewModel Domain Repository Form Screen
The Three Layers of State Where does e a ch st a te live? TextField focus state Keyboard visible/hidden Scroll position Wrong Layer == Bugs -
Ephemeral remember { } Screen ViewModel Domain Repository Form Screen
The Three Layers of State Where does e a ch st a te live? TextField focus state Keyboard visible/hidden Scroll position Form values (name, etc) Validation errors isLoading, isSaving Wrong Layer == Bugs -
Ephemeral remember { } Screen ViewModel Domain Repository Form Screen
The Three Layers of State Where does e a ch st a te live? TextField focus state Keyboard visible/hidden Scroll position Form values (name, etc) Validation errors isLoading, isSaving User pro fi le (from API) Saved pro fi le (in DB) Wrong Layer == Bugs -
Wrong Layer == Bugs Ephemeral remember { } Screen ViewModel
Domain Repository Form Screen The Three Layers of State The Rule -
Wrong Layer == Bugs Ephemeral remember { } Screen ViewModel
Domain Repository Form Screen The Three Layers of State Screen state here Form resets on rotation The Rule -
Wrong Layer == Bugs Ephemeral remember { } Screen ViewModel
Domain Repository Form Screen The Three Layers of State Screen state here Form resets on rotation Ephemeral state in ViewModel Keyboard survives navigation The Rule -
Wrong Layer == Bugs Ephemeral remember { } Screen ViewModel
Domain Repository Form Screen The Three Layers of State Screen state here Form resets on rotation Ephemeral state in ViewModel Keyboard survives navigation Screen logic trapped here Stale data a ft er back nav The Rule -
The Three Layers of State The Rule W h e
n Shou l d t h e s t at e di e ? State Machines -
The Three Layers of State The Rule - Dies with
recomposition → remember { } W h e n Shou l d t h e s t at e di e ? State Machines -
The Three Layers of State The Rule - Dies with
recomposition → remember { } - Dies with n a vig a tion → ViewModel W h e n Shou l d t h e s t at e di e ? State Machines -
The Three Layers of State The Rule - Dies with
recomposition → remember { } - Dies with n a vig a tion → ViewModel - Never dies → Repository W h e n Shou l d t h e s t at e di e ? State Machines -
State Machines The Boole a n Explosion Problem data class
Sc r eenState( val isLoading: Boolean = false, val isSaving: Boolean = false, val isE r r o r : Boolean = false, val isSuccess: Boolean = false, ) ViewModel State booleans 🫣 -
State Machines The Boole a n Explosion Problem data class
Sc r eenState( val isLoading: Boolean = false, val isSaving: Boolean = false, val isE r r o r : Boolean = false, val isSuccess: Boolean = false, ) 2⁴ = 16 possible combinations ViewModel State booleans 🫣 -
State Machines The Boole a n Explosion Problem data class
Sc r eenState( val isLoading: Boolean = false, val isSaving: Boolean = false, val isE r r o r : Boolean = false, val isSuccess: Boolean = false, ) 2⁴ = 16 possible combinations On l y 4 a r e v al id ViewModel State booleans 🫣 -
State Machines The Boole a n Explosion Problem data class
Sc r eenState( val isLoading: Boolean = false, val isSaving: Boolean = false, val isE r r o r : Boolean = false, val isSuccess: Boolean = false, ) 2⁴ = 16 possible combinations On l y 4 a r e v al id -
State Machines The Boole a n Explosion Problem data class
Sc r eenState( val isLoading: Boolean = false, val isSaving: Boolean = false, val isE r r o r : Boolean = false, val isSuccess: Boolean = false, ) 2⁴ = 16 possible combinations On l y 4 a r e v al id ViewModel -
State Machines The Boole a n Explosion Problem data class
Sc r eenState( val isLoading: Boolean = false, val isSaving: Boolean = false, val isE r r o r : Boolean = false, val isSuccess: Boolean = false, ) 2⁴ = 16 possible combinations On l y 4 a r e v al id ViewModel State booleans 🫣 -
State Machines The Boole a n Explosion Problem data class
Sc r eenState( val isLoading: Boolean = false, val isSaving: Boolean = false, val isE r r o r : Boolean = false, val isSuccess: Boolean = false, ) 2⁴ = 16 possible combinations On l y 4 a r e v al id ViewModel State booleans 🫣 E v e r y a c t ion c a n t ouch e v e r y fl a g -
State Machines Se a led Interf a ce Solution M
a ke IMPOSSIBLE STATES impossible -
sealed inte r face Sc r eenState { data object
Loading : Sc r eenState data class Editing(val fo r m: Fo r m) : Sc r eenState data class Saving(val fo r m: Fo r m) : Sc r eenState data class Success(val msg: St r ing) : Sc r eenState data class E r r o r (val r eason: St r ing) : Sc r eenState } State Machines Se a led Interf a ce Solution M a ke IMPOSSIBLE STATES impossible -
sealed inte r face Sc r eenState { data object
Loading : Sc r eenState data class Editing(val fo r m: Fo r m) : Sc r eenState data class Saving(val fo r m: Fo r m) : Sc r eenState data class Success(val msg: St r ing) : Sc r eenState data class E r r o r (val r eason: St r ing) : Sc r eenState } State Machines Se a led Interf a ce Solution M a ke IMPOSSIBLE STATES impossible 5 s t at e s. On ly 5. N o combin at ions. -
UniDirectional Pipe UI Events ViewModel Tr a nsition St a
te (se a led) UI Render Observes State Machines -
UniDirectional Pipe State Machines Lo a ding onLoad d a
t a lo a ded Editing -
UniDirectional Pipe State Machines Lo a ding onLoad d a
t a lo a ded Editing Error -
UniDirectional Pipe State Machines Lo a ding onLoad d a
t a lo a ded Editing Error Error Retry -
UniDirectional Pipe State Machines Lo a ding onLoad d a
t a lo a ded Editing Error S a ving Error Retry -
UniDirectional Pipe State Machines Lo a ding onLoad d a
t a lo a ded Editing Error S a ving Success Error Retry Success -
UniDirectional Pipe State Machines Lo a ding onLoad d a
t a lo a ded Editing Error S a ving Success Error Retry Success E a ch a rrow is a v a lid tr a nsition -
UniDirectional Pipe State Machines Lo a ding onLoad d a
t a lo a ded Editing Error S a ving Success Error Retry Success E a ch a rrow is a v a lid tr a nsition Missing a rrow = impossible tr a nsition -
UniDirectional Pipe State Machines VIEW INTENT MODEL VIEW (UI) (Event)
(State) (UI) Use r ──────> Submit ──────> Saving ──────> Show taps button Intent State Spinne r -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap var shouldProcess by
remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } State Anti-Patterns -
var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess)
{ if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline -
var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess)
{ if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns // ✅ Runs Timeline -
var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess)
{ if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns // ✅ Runs // 💀 Triggers c a ncell a tion Timeline -
var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess)
{ if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns // ✅ Runs // 💀 Triggers c a ncell a tion // ❌ NEVER RUNS Timeline -
var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess)
{ if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns // ✅ Runs // 💀 Triggers c a ncell a tion // ⏸ Suspension point // ❌ NEVER RUNS Timeline -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
shouldProcess = true —> L a nchedE ff ect st a rts var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
shouldProcess = true —> L a nchedE ff ect st a rts var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } doSomething() —> completes -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
shouldProcess = true —> L a nchedE ff ect st a rts var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } doSomething() —> completes shouldProcess = f a lse —> Key Ch a nged, c a ncell a tion scheduled -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
shouldProcess = true —> L a nchedE ff ect st a rts var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } doSomething() —> completes shouldProcess = f a lse —> Key Ch a nged, c a ncell a tion scheduled del a y(200) —> Coroutine suspends -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
shouldProcess = true —> L a nchedE ff ect st a rts var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } doSomething() —> completes shouldProcess = f a lse —> Key Ch a nged, c a ncell a tion scheduled del a y(200) —> Coroutine suspends Recomposition runs (~16ms) -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
shouldProcess = true —> L a nchedE ff ect st a rts var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } doSomething() —> completes shouldProcess = f a lse —> Key Ch a nged, c a ncell a tion scheduled del a y(200) —> Coroutine suspends Recomposition runs (~16ms) Key is ch a nged -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
shouldProcess = true —> L a nchedE ff ect st a rts var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } doSomething() —> completes shouldProcess = f a lse —> Key Ch a nged, c a ncell a tion scheduled del a y(200) —> Coroutine suspends Recomposition runs (~16ms) Key is ch a nged C a ncels old L a unchedE ff ect -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Timeline
shouldProcess = true —> L a nchedE ff ect st a rts var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(shouldProcess) { if (shouldProcess) { doSomething() shouldProcess = false delay(200) doImportantWork() } } doSomething() —> completes shouldProcess = f a lse —> Key Ch a nged, c a ncell a tion scheduled del a y(200) —> Coroutine suspends Recomposition runs (~16ms) Key is ch a nged C a ncels old L a unchedE ff ect doImport a ntWork() —> never re a ched -
ANTI-PATTERN #1: LaunchedE ff ect Self-Cancellation Trap State Anti-Patterns Fix
var shouldProcess by remember { mutableStateOf(false) } LaunchedE ff ect(Unit) { // Key never changes snapshotFlow { shouldProcess } . fi lter { it } .collect { doSomething() shouldProcess = false // Safe now delay(200) doImportantWork() // ✅ Runs } } Key is st a ble. St a te ch a nge doesn't kill the coroutine. -
Rule State Anti-Patterns LAUNCHEDEFFECT RULE If you ch a nge
the key inside the e ff ect... -
Rule State Anti-Patterns LAUNCHEDEFFECT RULE If you ch a nge
the key inside the e ff ect... ... a nd you h a ve a ny suspension point a fter... -
Rule State Anti-Patterns LAUNCHEDEFFECT RULE If you ch a nge
the key inside the e ff ect... Key = lifecycle Ch a nge key = rest a rt lifecycle Rest a rt = c a ncel previous ... a nd you h a ve a ny suspension point a fter... ...your code a fter th a t point won't run. -
Transitions Are Functions data class T r ansitionResult( val newState:
Sc r eenState, val effects: List<Effect> = emptyList() ) fun ScreenState.onSubmit(): TransitionResult = when (this) { is Loading -> TransitionResult(this) is Editing -> TransitionResult( newState = Saving(form), e fi ) is Saving -> TransitionResult(this) is Success -> TransitionResult(this) -
Transitions Are Functions data class T r ansitionResult( val newState:
Sc r eenState, val effects: List<Effect> = emptyList() ) fun ScreenState.onSubmit(): TransitionResult = when (this) { is Loading -> TransitionResult(this) is Editing -> TransitionResult( newState = Saving(form), e ff ects = listOf(E ff ect.SavePro fi le(form)) ) is Saving -> TransitionResult(this) is Success -> TransitionResult(this) is Error -> TransitionResult( newState = Saving(form), e ff ects = listOf(E ff ect.SavePro fi le(form)) ) } -
Transitions Are Functions r val newState: Sc r val effects:
List<Effect> = emptyList() ) fun ScreenState.onSubmit(): TransitionResult = when (this) { is Loading -> TransitionResult(this) is Editing -> TransitionResult( newState = Saving(form), e ff ects = listOf(E ff ect.SavePro fi le(form)) ) is Saving -> TransitionResult(this) is Success -> TransitionResult(this) is Error -> TransitionResult( newState = Saving(form), e ff ects = listOf(E ff ect.SavePro fi le(form)) ) } -
Transitions Are Functions r val newState: Sc r val effects:
List<Effect> = emptyList() ) fun ScreenState.onSubmit(): TransitionResult = when (this) { is Loading -> TransitionResult(this) is Editing -> TransitionResult( newState = Saving(form), e ff ects = listOf(E ff ect.SavePro fi le(form)) ) is Saving -> TransitionResult(this) is Success -> TransitionResult(this) is Error -> TransitionResult( newState = Saving(form), e ff ects = listOf(E ff ect.SavePro fi le(form)) ) } -
Transitions Are Functions r val newState: Sc r val effects:
List<Effect> = emptyList() ) fun ScreenState.onSubmit(): TransitionResult = when (this) { is Loading -> TransitionResult(this) is Editing -> TransitionResult( newState = Saving(form), e ff ects = listOf(E ff ect.SavePro fi le(form)) ) is Saving -> TransitionResult(this) is Success -> TransitionResult(this) is Error -> TransitionResult( newState = Saving(form), e ff ects = listOf(E ff ect.SavePro fi le(form)) ) } Pure function. No API calls inside. No side e ff ects. Just data in, data out. Why Pure functions? -
Why Pure functions? PREDICTABLE S a me input → s
a me output. Alw a ys. Effects as Outputs -
Why Pure functions? PREDICTABLE S a me input → s
a me output. Alw a ys. TESTABLE No mocks. No coroutines. Just a ssertions. Effects as Outputs -
Why Pure functions? PREDICTABLE S a me input → s
a me output. Alw a ys. TESTABLE No mocks. No coroutines. Just a ssertions. DEBUGGABLE Log every tr a nsition. Repl a y a ny bug. Effects as Outputs -
Effects as Outputs Side E ff ect a re outputs,
not inline code // ❌ E ff ect inside transition fun onSubmit() { _state.value = Saving(form) repository.save(form) // Side e ff ect here navigator.goTo(Success) // Another one } -
Effects as Outputs Side E ff ect a re outputs,
not inline code // ❌ E ff ect inside transition fun onSubmit() { _state.value = Saving(form) repository.save(form) // Side e ff ect here navigator.goTo(Success) // Another one } // ✅ E ff ects as data fun ScreenState.onSubmit() = TransitionResult( newState = Saving(form), e ff ects = listOf( E ff ect.SavePro fi le(form), E ff ect.Navigate(Routes.Success) ) ) -
Effect Types Common E ff ects sealed inte r face
Effect { data class ShowSnackba r ( val message: St r ing, val id: UUID = UUID. r andomUUID() ) : Effect data class Navigate(val r oute: St r ing) : Effect data class SaveToDatabase(val data: Fo r m) : Effect data class T r ackAnalytics(val event: St r ing) : Effect data object HapticFeedback : Effect } ViewModel Executes -
ViewModel Executes Effect Types class P r of i leViewModel
: ViewModel() { p r ivate val _state = MutableStateF l ow<Sc r eenState>(Loading) val state = _state.asStateF l ow() fun onSubmit() { val r esult = _state.value.onSubmit() _state.value = r esult.newState r esult.effects.fo r Each { execute(it) } } p r ivate fun execute(effect: Effect) = when (effect) { is Effect.SaveP r of i le - > viewModelScope.launch { r eposito r y.save(effect.fo r m) } is Effect.ShowSnackba r - > _snackba r .emit(effect) is Effect.Navigate - > _navigation.emit(effect. r oute) } } -
ViewModel Executes Effect Types class P r of i leViewModel
: ViewModel() { p r ivate val _state = MutableStateF l ow<Sc r eenState>(Loading) val state = _state.asStateF l ow() fun onSubmit() { val r esult = _state.value.onSubmit() _state.value = r esult.newState r esult.effects.fo r Each { execute(it) } } p r ivate fun execute(effect: Effect) = when (effect) { is Effect.SaveP r of i le - > viewModelScope.launch { r eposito r y.save(effect.fo r m) } is Effect.ShowSnackba r - > _snackba r .emit(effect) is Effect.Navigate - > _navigation.emit(effect. r oute) } } -
ViewModel Executes Effect Types class P r of i leViewModel
: ViewModel() { p r ivate val _state = MutableStateF l ow<Sc r eenState>(Loading) val state = _state.asStateF l ow() fun onSubmit() { val r esult = _state.value.onSubmit() _state.value = r esult.newState r esult.effects.fo r Each { execute(it) } } p r ivate fun execute(effect: Effect) = when (effect) { is Effect.SaveP r of i le - > viewModelScope.launch { r eposito r y.save(effect.fo r m) } is Effect.ShowSnackba r - > _snackba r .emit(effect) is Effect.Navigate - > _navigation.emit(effect. r oute) } } -
Async State Machines ASYNC = EXPLICIT STATES sealed inte r
face Async<out T> { data object Idle : Async<Nothing> data object Loading : Async<Nothing> data class Success<T>(val data: T) : Async<T> data class E r r o r (val e r r o r : Th r owable) : Async<Nothing> } / / Usage: data class P r of i leSc r eenState( val p r of i le: Async<Use r P r of i le> = Async.Idle, val saveStatus: Async<Unit> = Async.Idle ) -
Async State Machines WHY ASYNC<T>? C a ncell a tion
Job c a ncelled → b a ck to Idle Not stuck in Loading forever -
Async State Machines WHY ASYNC<T>? C a ncell a tion
Job c a ncelled → b a ck to Idle Not stuck in Loading forever MULTIPLE REQUESTS E a ch oper a tion gets its own Async<T> No boolean fl ags colliding -
Async State Machines WHY ASYNC<T>? C a ncell a tion
Job c a ncelled → b a ck to Idle Not stuck in Loading forever MULTIPLE REQUESTS E a ch oper a tion gets its own Async<T> No boolean fl ags colliding RETRY Error holds throw a ble. User taps retry → Loading again -
Testing TESTING: NO MOCKS NEEDED @Test fun `submit f r
om Editing t r ansitions to Saving`() { val state = Sc r eenState.Editing(fo r m = testFo r m) val r esult = state.onSubmit() asse r tThat( r esult.newState).isEqualTo(Saving(testFo r m)) asse r tThat( r esult.effects).containsExactly( Effect.SaveP r of i le(testFo r m) ) } -
Testing TESTING: NO MOCKS NEEDED @Test fun `submit while Saving
is igno r ed`() { val state = Sc r eenState.Saving(fo r m = testFo r m) val r esult = state.onSubmit() asse r tThat( r esult.newState).isEqualTo(Saving(testFo r m)) asse r tThat( r esult.effects).isEmpty() } -
Avoiding AntiPatterns Sn a ckb a r Shows Twice //
Bad: ❌ State-based one-time event val error by viewModel.error.collectAsState() LaunchedE ff ect(error) { error?.let { snackbarHostState.showSnackbar(it) // Rotation → resubscribes → shows again } } -
Avoiding AntiPatterns Sn a ckb a r Shows Twice //
Good: ✅ E ff ect with unique ID data class ShowSnackbar( val message: String, val id: UUID = UUID.randomUUID() ) LaunchedE ff ect(e ff ect?.id) { e ff ect?.let { snackbarHostState.showSnackbar(it.message) viewModel.consumeE ff ect() } } -
Avoiding AntiPatterns Forgotten Remember / / Bad: ❌ New instance
eve r y r ecomposition @Composable fun Counte r () { va r count = mutableStateOf(0) / / No r emembe r ! Button(onClick = { count.value + + }) { Text("Count: ${count.value}") / / Always 0 } } -
Avoiding AntiPatterns / / Good:✅ Su r vives r ecomposition
@Composable fun Counte r () { va r count by r emembe r { mutableStateOf(0) } Button(onClick = { count + + }) { Text("Count: $count") } } Forgotten Remember -
Avoiding AntiPatterns B a ckw a rds Write = In
f inite Loop / / Bad:❌ W r ite afte r r ead = inf i nite r ecomposition @Composable fun B r oken() { va r count by r emembe r { mutableStateOf(0) } Text("$count") / / Read count + + / / W r ite → t r igge r s r ecomposition → r epeat } -
Avoiding AntiPatterns / / Good: ✅ W r ite only
in callbacks @Composable fun Fixed() { va r count by r emembe r { mutableStateOf(0) } Text("$count") Button(onClick = { count + + }) { / / W r ite in event Text("Inc r ement") } } Forgotten Remember -
Avoiding AntiPatterns derivedSt a teOf Misue / / Useless: ❌
Output changes as often as input - no benef i t va r f i r stName by r emembe r { mutableStateOf("") } va r lastName by r emembe r { mutableStateOf("") } val fullName by r emembe r { de r ivedStateOf { "$f i r stName $lastName" } / / Pointless } -
Avoiding AntiPatterns derivedSt a teOf Misue / / ✅ Just
compute it val fullName = "$f i r stName $lastName" Co r r ect use: / / ✅ Output changes LESS than input val listState = r emembe r LazyListState() val showButton by r emembe r { de r ivedStateOf { listState.f i r stVisibleItemIndex > 0 } } / / Sc r oll position changes eve r y pixel / / Boolean changes r a r ely -
Avoiding AntiPatterns collectAsSt a te vs collectAsSt a teWithLifecycle Wasteful:
/ / ❌ Keeps collecting when app backg r ounded val state by viewModel.state.collectAsState() Bette r : / / ✅ Lifecycle - awa r e - pauses when STOPPED val state by viewModel.state.collectAsStateWithLifecycle() collectAsState: App backg r ounded → still collecting → batte r y d r ain collectAsStateWithLifecycle: App backg r ounded → paused → r esumes when visible -
Avoiding AntiPatterns Unst a ble L a mbd a C
a ptures / / Bad: ❌ New lambda eve r y r ecomposition @Composable fun Pa r ent() { va r text by r emembe r { mutableStateOf("") } Child(onClick = { doSomething() }) / / New instance each time TextField(value = text, onValueChange = { text = it }) } / / TextField updates → Pa r ent r ecomposes → new lambda → Child r ecomposes -
Avoiding AntiPatterns Unst a ble L a mbd a C
a ptures / / Good: ✅ Stable lambda @Composable fun Pa r ent() { va r text by r emembe r { mutableStateOf("") } val onClick = r emembe r { { doSomething() } } Child(onClick = onClick) / / Same instance TextField(value = text, onValueChange = { text = it }) } -
Climax Four Rules Sep a r a te Model Emit
Test State lives where its lifecycle matches -
Climax Four Rules Sep a r a te Model Emit
Test Sealed inte rf aces, not boolean bags State lives where its lifecycle matches -
Climax Four Rules Sep a r a te Model Emit
Test Sealed inte rf aces, not boolean bags State lives where its lifecycle matches E ff ects as outputs, not inline code -
Climax Four Rules Sep a r a te Model Emit
Test Sealed inte rf aces, not boolean bags State lives where its lifecycle matches E ff ects as outputs, not inline code Pure functions, no mocks