From official we know
The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way
But i think lot of developers use ViewModel
as both data store and controller(like calling repository, network client for data). I also use as for both data store and controller for view.
Android official sample code has also some controller logic. From official :
class MyViewModel : ViewModel() {
private val users: MutableLiveData<List<User>> by lazy {
MutableLiveData().also {
loadUsers()
}
}
fun getUsers(): LiveData<List<User>> {
return users
}
private fun loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
Here loadUsers
may calling some Repository or NetworkClient . So here it acting like controller.
I am sure many developer do this way, but as from definition ViewModel
should store and manage UI related data, should ViewModel
act as a Controller ?
I found some stackoverflow thread this and this about this.
First one accepted answer suggested not to use use ViewModel
as Controller and to use a Controller for other task.
In comment section of Second one @commonsware also suggested not to use complicated things other than data.
So my question is
- What will be the actual responsibility of
ViewModel
from architectural concept? - If i have to do some method calls related to View [like data query, network call and other business login related stuff ] where should i do it?
- and if i have to use a Controller then how i connect
View
and Controller for device rotation and sharing controller between Fragment ?
Hope my question is clear to all
Thanks in advance.