When we open sourced Compose at I/O 2019, one of the most common questions from many Android developers was “What does this mean for the architecture of our apps?”
At the same time, there’s been a lot of discussion inside and outside of Google about architecture in Compose apps.
Everything from an AppNavigator down to a Button is a composable. So the architecture of your UI can fit the architecture of your app.
LiveData 👉 developer.android.com/reference/kotl…
Flow 👉 developer.android.com/reference/kotl…
RxJava2 👉 developer.android.com/reference/kotl…
As we explored this, we realized we'd need a way to use ViewModels in Compose. So, we introduced a new API
viewModel 👉 developer.android.com/reference/kotl…
This applies both to big architectures like what you build Android Architecture Components, as well as a single composable.
As you add state to a composable by using ViewModel, you couple that composable with the ViewModel. It becomes stateful.
Stateful composables are harder to reuse, harder to test, and tend to be more complicated.
stateful 👉 github.com/android/compos…
stateless 👉 github.com/android/compos…
And, stateless composables are easier to reuse, test, and tend to be simpler.
To showcase ViewModels and LiveData used in a unidirectional data flow in Compose, we aimed to refactor JetNews to use ViewModel with the alpha launch.
Here's the commit that refactors JetNews to use ViewModel
github.com/android/compos…
github.com/android/compos…
Instead of creating a new ViewModel when entering a screen, it re-used the old one. The details screen would show the wrong article. Uh oh.
github.com/android/compos…
It also destroyed the ViewModel on rotation – so we decided to ❌ ship.
Here's ArticleScreen after replacing ViewModel with a new arch.
github.com/android/compos…
This commit was a complete refactor of the app's architecture and the total change was one composable per screen.
github.com/android/compos…
To learn more check the codelab Using State in Jetpack Compose.
👉 developer.android.com/codelabs/jetpa…