StateFlow with One- and TwoWay-DataBinding on Android
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.
The first step is to create the layout file that will have StateFlow
field bound to TextView
with OneWayBinding
and another instance of StateFlow
bound to TextInputEditText
with TwoWayBinding
.
No comments:
Post a Comment