why should we use ViewModel if we can directly access Repository from Fragment in MVVM

Viewed 1601

I am a beginner and I would like to know that why we use ViewModel in MVVM, when we can directly access Repository and call Repository functions from Fragment. This approach seems easier. Please see below details why I ask this question.

In case you would like to see the codes, please refer below question in Stackoverflow:

Recycler view shows all data from Room database instead of just showing data of selected ids

I had a problem where I wanted to show details of a selected id in RecyclerView, but when I was using ViewModel the RecyclerView always showed the details of all ids. Then instead of accessing Repository through ViewModel, I directly accessed the Repository and solved the problem. Now the RecyclerView shows details of only the selected id.

2 Answers

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

The Android framework manages the lifecycles of UI controllers, such as activities and fragments. The framework may decide to destroy or re-create a UI controller in response to certain user actions or device events that are completely out of your control.

If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. For example, your app may include a list of users in one of its activities. When the activity is re-created for a configuration change, the new activity has to re-fetch the list of users. For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps.

Another problem is that UI controllers frequently need to make asynchronous calls that may take some time to return. The UI controller needs to manage these calls and ensure the system cleans them up after it's destroyed to avoid potential memory leaks. This management requires a lot of maintenance, and in the case where the object is re-created for a configuration change, it's a waste of resources since the object may have to reissue calls it has already made.

It's easier and more efficient to separate out view data ownership from UI controller logic.

For more info and sample check this

you have to separate your business logic from the UI logic also you can do better exception handling when you use view model and use repository for the data connection.

you have applied wrong logic. to solve the above problem send data from your activity to view model and view model to the repository and then get data from ViewModel to the activity of that particular id. Hops this will helpful for you.

in Activity

viewmodel1.ProfileFetch(id)

then in ViewModel

 fun ProfileFetch(id:String?) {
        Coroutines.main {
            try {
                val response = repository.StudentProfile(id)
                response?.let {
                    if(response.statusResponse!!.statusCode.equals("1")){
                        Log.v("sssss","ppppppp")
                        studentProfileResponseListner?.onSuccess(response)
                    }else{
                        studentProfileResponseListner?.onFailure(response!!.statusResponse?.message)
                    }
                }

            } catch (e: ApiException) {
                studentProfileResponseListner?.onFailure(e.message!!)
            } catch (e: NoInternetException) {
                studentProfileResponseListner?.onFailure(e.message!!)

            } catch (e: SocketTimeoutException) {
                studentProfileResponseListner?.onFailure("Network is unreachable")

            } catch (e: Exception) {
                studentProfileResponseListner?.onFailure("Sorry for inconvenience, system has encountered technical glitch")

            }
        }
    }

pass id from ViewModel to the repository

  val response = repository.StudentProfile(id)
Related