This article is about how to structure your App using Jetpack Compose.
I won’t be talking about how to create your first composable function, they are already tons of articles on that subject.
Jetpack Compose, is brand new UIToolKit, based on functional and declarative principles that helps you create innovative and beautiful UI for Android (and some other platforms).
Fragments are dead, what’s replacing them?
In today’s Android world (yet Compose is still beta), we architecture our apps with the following hierarchy:
- Fragment1 + ViewModel1
- Fragment2 + ViewModel2 - ActivityB
- Fragment3 + ViewModel3
So now that we are removing Fragments from the equation, what is the equivalent and what do we do with the ViewModels?
Well let’s remember that MVVM stand for
And a fragment is nothing but a view (and that’s why you should refrain adding any business logic into them).
With Compose you can replace your Fragment by Composable function which act as your View.
Let’s illustrate that with the following App concept. It is a simple 2 screens app, you can go from screen 1 to screen 2 and from screen 2 to screen 1.
Each screen has a View and a ViewModel
In the activity we are going to instantiate the Views and the ViewModels
Just like we were providing the ViewModel to fragment (using the ktx or the ViewModel provider), we need to provide the ViewModel to the Composable function as a parameter. You will need to have your ViewModel instantiated in your activity, so you can provide it to the Composable function.
Activity.ktprivate val screen1ViewModel: Screen1ViewModel by viewModels()