How to implement a change method in Android ViewModel

Viewed 144

I'm studying the GithubBrowserSample source and I see that it has only queries/get methods, I mean, it only request data and does not do any update/change/post to the rest api.

For example, UserViewModel.kt has the code below:

val user: LiveData<Resource<User>> = _login.switchMap { login ->
    if (login == null) {
        AbsentLiveData.create()
    } else {
        userRepository.loadUser(login)
    }
}

fun setLogin(login: String?) {
    if (_login.value != login) {
        _login.value = login
    }
}

So basically, I call setLogin and the user LiveData will call userRepository.loadUser(login) if there's an observer, this looks good to me and no questions here. However, how would I implement something like UpdateUserProfile?

If I follow the same pattern, I would create a method like fun updateUserProfile(userProfile: userProfile) and this method would set the userProfile to a LiveData and then I would need to have an observer observing that LiveData in order to have userRepository to call updateUserProfile.

But it doesn't make sense to me.

So what's the best/recommended way to do this?

1 Answers

It depends on what your data exactly is and what you're trying to show:

  1. If your UserProfile is not something that you show on the UI, then you could just call the network request and update the user livedata with the new information. (You can do this with multiple options, happy heuristic - update before request finishes & reset on error, or just update the user when request finishes)
  2. If you show the UserProfile separately from the user information, then you probably would create a LiveData/Observable for it and update accordingly when the request finishes.

TL;DR I wouldn't follow the same pattern here, since I don't think it applies: In the first case probably login is shown separately from the UI and they implemented a reactive pattern to listening to these changes and fetching the user information. In your case you don't have login + user, you just have userProfile

Related