Making ViewModel Observable
While making android applications, we tend to follow some kind of design pattern or try to architect our application using some of the common patterns like MVVM, MVP, MVC or any other to simply the code readability and make the code more testable.
MVVM is the one that makes a good effort in making out business logic completely testable in isolation. When I started using it, initially I thought that it’s like a simple model, which can be binded with the UI using data binding. But as I started to dig in more, I came to know that it can do more then that, like it can survive the configuration changes if we use the “AndroidViewModel” and provide the view model binding using the “ViewModelProviders.of(this)”.
But prior to moving on that, we need to understand that whenever we change the data of ViewModel, it gets reflected to the UI components with whihc our ViewModel binded to, and all happens because of the class
BaseObservable that we tend to use with the normal ViewModel(not the AndroidViewModel) by calling in the method
notifyChange() and as in Java/Kotlin we only can extend from one class, we either can use the
AndroidViewModel, or the
BaseObservable. We cannot use both of them together
The best solution is to look into
BaseObservable and try to understand, that what it does, in order to notify changes to UI whenever the ViewModel Data is changed and If you go in there and you will see that it implements an interface i.e,
and if you go into the
Observable interface you will see that there are two method declarations and one abstract class is declared in it which has
onPropertyChanged which is called by an
Observable whenever an observable property changes.
Now we understand that how
BaseObservable utilizes the
Observable interface and uses
PropertyChangeRegistry which in the end helps in notifying the changes to the UI and load in the ViewModel.
What are we waiting for?
we just need to make a custom ViewModel class lets name it
ObservableViewModel and extend from the
AndroidViewModel and implement the
Observable interface, and then implement all the methods of it and that will be all.
now the last thing that we need to do is to extend this class instead of AndroidViewModel and call in the
notifyChange() if you want to update all the views, or call in the
notifyChange(viewId) just to update a specific element whenever you want.
notifyChange()on line 20, in its body we are calling
mCallBacks.notifyChange(this, 0), here 0 means update every property.
If you liked this article, don’t forget to clap, comment on it and share with your friends.