ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

StateFlow with One- and TwoWay-DataBinding on Android

Anastasia Finogenova
ProAndroidDev
Published in
3 min readFeb 11, 2021
Android MVI with Kotlin Coroutines & Flow — QuickBird Studios Blog

There has been a lot of talk in the Android community related to LiveData being deprecated in favor of StateFlow. This doesn’t seem to be the case but with the canary release of Android Studio Arctic Fox | 2020.3.1 (before the naming change it would have been 4.3) the last piece of moving away from LiveData is complete — DataBinding is enabled for StateFlow.

Let’s check out how this works exactly.

From the initial glance the DataBinding works with StateFlow with minimum changes.

As the release notes state — For Kotlin apps that use coroutines, you can now use StateFlow objects as a data binding source to automatically notify the UI about changes in the data. Your data bindings will be lifecycle aware and will only be triggered when the UI is visible on the screen.

To use a StateFlow object with your binding class, you need to specify a lifecycle owner to define the scope of the StateFlow object, and in your layout, assign the properties and methods of your ViewModel component to the corresponding views using binding expressions, as shown in the following basic example:

class ViewModel() {
val username: StateFlow<String>
}
//code in xml
<TextView
android:id="@+id/name"
android:text="@{viewmodel.username}" />

This looks exactly as we would use LiveData before — so far so good! 😃

If you’re in a Kotlin app that uses AndroidX, StateFlow support is automatically included in the functionality of data binding, including the coroutines dependencies. As described in Bind layout views to Architecture Components, data binding works seamlessly with ViewModel objects.

Now as we have grasped the gist of it, let’s jump into a custom example.

Here is a sample app I have created to test out One- and TwoWay- Binding with StateFlow. The app is loading friends’ names from the data source and also uses TwoWayBinding to accept user’s input and append it to the names.

Demo of OneWayBinding to TextView and TwoWayBinding to EditText

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Responses (2)

Write a response