Android Architecture Patterns Part 3: Model-View-ViewModel
Florina Muntenescu
4.1K16

Should the data fetching code be inside the View layer (activity, fragment) or inside the ViewModel layer?

If the answer is the ViewModel layer, does it make sense to have the ViewModel which fetches the data, output more ViewModels if necessary? This is assuming the outputted ViewModels is a derivative of the data.

For example, consider a UserActivity that displays a List<UserViewModel>. Would it make sense to have a UserActivityViewModel which has a reference to the UserDataModel (or some class abstraction fetching data from data source) to fetch the data, and then create UserViewModels from the list of User models it gets and return that back to the UI layer. Some example code like the following (Kotlin and using LiveData instead of Observable).

class UserActivityViewModel {
    var userModel: UserDataModel = // …
    var users: LiveData<ArrayList<UserViewModel>>?= null
    fun fetchUsers() : LiveData<List<UserViewModel>> {
        val users: List<User>= userModel.getUsers()
        // construct UserViewModel, where each UserViewModel                //abstracts UI state of each user in the list
        users.set(users.map{ user -> UserViewModel(user) })
return users
    }
}
class UserActivity {
val viewModel: UserActivityViewModel
    // ... 
onCreate() {
       viewModel.fetchUsers().observe(..)
}
}