What is the best way to name methods in the ViewModel classes? Based on its action/behavior or the lifecycle of the Activity/Fragment?
For example:
Methods named by its action
override fun onResume() {
super.onResume()
viewModel.connect()
}
override fun onPause() {
super.onPause()
viewModel.disconnect()
}
override fun onItemCheckedChanged(task: Task, value: Boolean) =
viewModel.updateTaskStatus(task, value)
Methods named by Android lifecycle
override fun onResume() {
super.onResume()
viewModel.onResume()
}
override fun onPause() {
super.onPause()
viewModel.onPause()
}
override fun onItemCheckedChanged(task: Task, value: Boolean) =
viewModel.onItemCheckedChanged(task, value)
There are several examples in the internet and the two approaches are used.
In my opinion, the methods should be related to the lifecycle, in this way the View does not need to know the logic behind the ViewModel, it just need to know that a lifecycle method need to be called.
What is the best approach?
There is not a correct way, as long as the code is clean and easy to read/understand. But if you look at the examples Android give, they show methods similar to the ones you posted.
1) One of the ways is to have an object with the methods named by Android lifecycle (Which you mentioned).
Each function is manually called within the lifecycle owner like so:
2) However, if you want to name the methods by their actions, you could accompany them methods with the OnLifecycleEvent annotation, which was excitingly brought to us in Android Jetpack! So for example:
Now these methods are called automatically with the help of a LifecycleObserver which can observe a LifecycleOwner:
The
LifecycleOwneris typically an Activity or Fragment. Up to you which one you choose, however my preferred is theLifecycleObserveras it requires less code, which I think makes it look cleaner.If your interested in good Android practices and some tips to help you along the way, there are a few good pages I would recommend:
- Android best practices
- Android tips & tricks
- Android must have libraries