Introduction to Android Architecture Components under 10 minutes

Introduction to Android Architecture Components under 10 minutes


Hello In I/O 17 Google made two major announcements for Android app developers. First one was of course Kotlin and second one was Architecture components. In fact Architecture components didn’t get much buzz because by the time it was announced most of the developers had left to learn Kotlin 🙂 Let’s first address the elephant in the room. and the elephant is: Lifecycle. The unique and challenging feature of the Android framework. On desktop a user clicks an app, opens it works on it and closes it. That is the lifecycle but on Android an Activity which is a representation of an app might get created multiple times during a single user experience. Let’s see what kind of challenges this brings to us. Memory leak There is an object which holds a reference of an Activity and for some reason that Activity gets recreated so the older instance get destroyed but it can’t be garbage collected because the reference of that Activity is being held by another object. This leads to memory leak. In fact this is such an issue that beginners at early stage need to learn how to avoid them. AsyncTask these days are mostly used to teach us how memory leak happens 🙂 Data persistence Suppose in your Activity in onCreate() method You are fetching some data and for some reason Activity gets recreated Maybe user changed the orientation. The onCreate() is called again and the data is fetched again which was not required. User didn’t ask for it so this leads to inefficiency. What has Google offered? Google wants to be more opinionated how apps should be developed and more guidance to the developers. It’s not providing a solution but a tool in the form of architecture components using which we can create better apps. Architecture components, there are two sections One is lifecycle related which contains classes like LifecycleOwner, LifecycleObserver and then there are components related to data persistence like LiveData, ViewModel and Room Let’s discuss them briefly one by one What is LifecycleOwner? LifecycleOwner is an interface and any class which implements it becomes a LifecycleOwner Currently Google provides us two classes. LifecycleActivity and LifecycleFragment which are LifecycleOwner The important thing is LifecycleOwner contains a LifecycleObject which sends notification about Lifecycle events to its Observer LifecycleObserver This is an interface and implemented by those classes which want to receive lifecycle events and those events are received thru annotations Let’s discuss lifecycle classes in slightly more detail Lifecycle is an abstract class. It has two enum and few methods. Enum State has values INITIALIZED, CREATED, STARTED etc. This is something new We used to get events which was for a moment but now there are states which we can enquire and find in which state a lifecycle is. Event enum has values ON_CREATE, ON_START etc. which we usually get in our Activity or Fragment and then there are methods to manage observers. LifecycleRegistry class it extends Lifecycle class. It manages observers and pass on lifecycle events to those observers. LifecycleOwner is an interface it has only one method getLifecycle() and it returns a Lifecycle object LifecycleregistryOwner, it extends LifecycleOwner interface and it overrides getLifecycle() method and returns LifecycleRegistry object. and then finally comes the LifecycleActivity which we are going to use as a LifecycleOwner It implements LifecycleRegistryOwner It overrides the method getLifecycle() and return an object mRegistry of class LifecycleRegistry Let’s see how LifecycleObserver and LifecycleOwner works MyLifecycleObserver implements LifecycleObserver interface LifecycleObserver interface doesn’t contain any method It’s just there to mark this class as as a LifecycleObserver In its constructor we are passing LifecycleOwner object and then we are calling getLifecycle() method which returns a Lifecycle object and then we call addObserver() method of Lifecycle object and pass the instance of this LifecycleObserver class lifecycle events are received thru annotations As you saw, no miracles happened. We already get lifecycle events in our Activity and Fragment Now we can get it in LifecycleObserver classes Not a big deal but then it provides a better separation. Our Activity and Fragment’s OnStart() onStop(), these methods wouldn’t be cluttered This separation from architectural point of view is a good move and it will lead to a clean code. Now let’s discuss data components LiveData is a class with generic type it’s a wrapper to a data which can be observed It’s a lifecycle aware which means it gets lifecycle events. Here is an example. We create an Observer object, MyObserver then we call LiveData’s observe() method and we pass the LifecycleOwner object as well as myObserver object Now this LifecycleOwner object which we have passed LiveData uses it to observe lifecycle events that’s how it knows when to send us data and when not to. CORRECTION: The best thing about ViewModel class is it helps to separate data. The way we get an object of ViewModel class in our Fragment or Activity is we call ViewModelProviders of() method and then pass the instance of Fragment or Activity then we call get() method and pass MyViewModel.class ViewModel is perfect container for LiveData as it persists configuration change, so it solves our issue of fetching the same data again and again. Sharing data between fragments of an Activity is easy. In Fragment instead of passing the instance of the Fragment in of() method we pass the instance of Activity using getActivity() so it returns the ViewModel object of the Activity. Don’t put any references of Activity or Fragment to avoid memory leak. ViewModel persists configuration change so it doesn’t match the lifecyle of Activity or Fragment. Room is an object mapping library for SQLite. Those of us who fetch cursor from SQLite know that we have to iterate thru the cursor, extract the data, put them in POJOs maybe create a List of POJOs. The good thing is all this is done by Room automatically Room has less boilerplate code as compared to what we use for SQLite. Room is intelligent also. so with these two line code we are getting a list of users matching a name with a particular keyword. Room also checks error at compile time so this should help us find out bugs. Observability Room can also return LiveData and this is how all these components connect. So, we have LifecycleActivity / LifecycleFragment which contains ViewModel which contains LiveData returned by Room. and then Room also supports RxJava2 Here is the overview of architecture components We have Activity / Fragment which observes LiveData held inside ViewModel ViewModel fetches it from repository and repository fetches it either from Room or remote data source. Here repository is an abstraction layer. We could have directly called Room from ViewModel but using this abstraction layer, repository we are being flexible with data sources Road map Architecture library is in alpha version right now, hopefully soon we can get a stable version. It requires Android Studio version 2.3 or higher. Currently there are two new classes introduced LifecycleActivity and LifecycleFragment which are LifecycleOwner. Later these classes will be merged respectively with AppCompatActivity and Fragment so we can use them normally as we do now. What next? Google has picked up popular practices and tried to implement them in Android framework. This shall reduce the learning curve and hopefully motivate more developers to use them. I would say again these are not solutions to a problem but tools to improve our apps. I would suggest to go ahead and read the architecture guide read the documentation, try out the code labs. I have put few links in the description box. You might find them useful. Thank you.

Leave a Reply