1

In Jetpack Compose, most examples look something like this:

ScreenLevelContainer {
  TopBar { ... }
  ContentA { ... }
  ContentB { ... }
  // etc.
}

Contents of any given composable may be comprised of other deeply nested composables.

They talk about "state hoisting" such that application state should be stored at the high levels in the UI, or outside the UI entirely.

There seems to be a maintenance problem here though. Any state that TopBar, its children, or the other content relies on needs to be passed through ScreenLevelContainer, even though ScreenLevelContainer has no explicit interest in the inner workings of TopBar.

Moreover, if any of these children ever need to update the state that they take, one needs to go update any parents that include them, possibly in lots of places in a sufficiently complex application.

Pre-Compose, I would have used dependency inversion (and probably dependency injection) to solve this:

val topBar = TopBar(/* TopBar specific arguments */)
val contentA = ContentA(/* ContentA specific arguments */)
val contentB = ContentB(/* ContentB specific arguments */)
ScreenLevelContainer(topBar, contentA, contentB)

In the above code, any changes to TopBar or the other content can happen independently of ScreenLevelContainer. This becomes especially valuable when nested UI becomes complex. (Imagine TopBar having an interactive shopping cart in it.)

What is the correct approach here?

dave mankoff
  • 17,379
  • 7
  • 50
  • 64
  • It's a pretty open-ended question, you will find a number of options in official developer documentation & videos. E.g. ViewModel, custom data/state objects (also in receiver position), slots, possibly even CompositionLocals depending on the particular use case. Hilt & androidx navigation have their own approaches in addition. Also, traditional ViewModels are being actively replaced in current androidx-lifecycle-viewmodel alphas/betas, so that could be something to look into, too. – Uli May 15 '22 at 18:58
  • Wait what's replacing ViewModels? – Richard Onslow Roper May 15 '22 at 22:45
  • Also see https://github.com/androidx/androidx/blob/androidx-main/compose/docs/compose-api-guidelines.md for guidance – Uli May 16 '22 at 10:16

0 Answers0