Thursday, 13 May 2021

How to implement a change method in Android ViewModel

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?



from How to implement a change method in Android ViewModel

No comments:

Post a Comment