Android Components investigation – part 1 – ViewModel and Lifecycle aware components

In this post I will try use newly released android components for the real-life application example. Lets start from ViewModel class and new approach to handle android lifecycle. Full project example can be found on my github, brach databinding.

For this, I will create dumb Login screen:

I’m going to use Kotlin language to write the application and android binding library to connect UI and logic code. Described screen can be implemented with the following xml:

As we use android binding library, our screen will use own ViewModel class – LifecycleAwareVM, other widgets are placed inside ConstraintLayout, but any other container may be used here. Right now LifecycleAwareVM is empty class, and the code of activity is:

Now we can launch the application, fill some input fields, check conditions mark and rotate the screen:

Everything looks nice. Screen looks as we desired to and preserves the state after rotation. Lets implement some simple logic – let the Login button be disabled by default and be enabled after user checks agree mark.

The simples way to implement this – is to update LifecyleAwareVM class

and connect it with the xml:

Now both view and view model are connected. Please note, that two-way databinding connection is used for the CheckBox. After launching the application we get next behaviour:

Botton enabling state is controlled now with the check box, but the state of the screen is lost during rotation. This is because activity lifecycle – activity is paused and closed on rotation, so new view model will be created during onCreate() callback. New LifecyleAwareVM is initiated with isConditionsAccepted = false.

In order to fix this we should store viewModel in the onSaceInstanceState() callback, ViewModel from android components cannot be used here. On the google’s issue tracker there is an issue about databinding-livedata connection. Google engineer states that such an integration will be implemented later, when android components will hit 1.0.

So, to implement this screen with AC (android components) we need to remove databinding implementation. That will be described in the next post.

Leave a Reply