Search code examples
androidmvvmviewmodel

Should an activity without connection to a repository have a ViewModel?


I am trying to understand MVVM on Android.

Assuming I have this simple application: (behaviour like Google contact app)

  • ListActivity: List of contacts from server
  • DetailActivity: detail screen of one contact (opened by click on list item)

For this list it is pretty clear how to implement mvvm pattern:

  • Activity is observing live data from view model and is updating recycler view
  • ViewModel: getAllContacts from repository
  • Repository: getAllContacts from server/DB/etc..

If the user clicks now on a contact in the list Detail screen will open: ListActivity does putExtra(“CONTACT”, chosenContact) and is starting detailActivity

DetailActivity is getting this ContactObject and is creating this view:

  • show image
  • show name
  • create contact options (call, sms, video)

As you can see in my example DetailScreen is not communicating with repository. It has already received all needed data from intent.


Questions:

  1. Should you create a view model for this detailActivity?
  2. If yes, what are the tasks of this view model if there is no connection to a repository needed?
  3. In google contacts app I have the options to delete a contact and to add contact to favorites. These should be done in a viewModel and this ViewModel needs a connection to a repository? Tasks of DetailActivity like call, send message, video call or share contact need context so as far as I understand MVVM they should be done in Activity class?

Solution

  • Should you create a view model for this detailActivity?

    In your case there is no need for it.

    If yes, what are the tasks of this view model if there is no connection to a repository needed?

    ViewModel helps a lot keeping state of an activity/fragment. If you had a spinner, or a checkbox, or any other field that could change, like a description text field inserted by the user, viewmodel would help keep the data even when the user rotates the phone.

    In google contacts app I have the options to delete a contact and to add contact to favorites. These should be done in a viewModel and this ViewModel needs a connection to a repository?

    Yes, your UI would call a fun in your viewmodel that would send to the repository, etc.

    Tasks of DetailActivity like call, send message, video call or share contact need context so as far as I understand MVVM they should be done in Activity class?

    Exactly, there is no need to use the viewmodel to send an intent to share a contact with another app, for instance.