Activity and Fragment binding
Like with Android's View
s, we may want to listen for Field
's changes on an Activity
or on a Fragment
.
To do so, the paradigm is the same we used on View
s: the extension functions asLifecycleOwner()
or asUIThreadLifecycleOwner()
return a LifecycleOwner
that will call callbacks respectively on the thread that made the change or on the UI thread. Moreover, this LifecycleOwner
respects the lifecycle of the Activity
or Fragment
: in particular, the callbacks will stop when the Activity
or Fragment
enter the stopped state, and will resume when they enter the started state.
Like with View
s, the library provides extension functions for both Activity
and Fragment
for calling listen()
directly without using asUIThreadLifecycleOwner
.
Suppose that we have an object called theme
that contains some Field
s that specify the aspect of the app, and one of those Field
s is the background color the app should have.
To react to changes to that Field
, we can do the following:
activity.asUIThreadLifecycleOwner().listen(theme.backgroundColor) { //Will be called on the UI thread
activity.window.decorView.setBackgroundColor(it)
}
ActivityListenUtils.asUIThreadLifecycleOwner(activity).listen(theme.backgroundColor, bg -> { //Will be called on the UI thread
activity.getWindow().getDecorView().setBackgroundColor(bg)
});
Equivalently:
activity.listen(theme.backgroundColor) { //Will be called on the UI thread
activity.window.decorView.setBackgroundColor(it)
}
ActivityListenUtils.listen(theme.backgroundColor, bg -> { //Will be called on the UI thread
activity.getWindow().getDecorView().setBackgroundColor(bg)
});
The simplicity of this approach allows to react to changes that usually are not handled dynamically, but are only handled when the Activity
starts.
Please note that although the example uses Activity
, the same code can be used on Fragment
s as well.