2

I am making an app with some friends, and we have decided to go with the MVVM pattern. However, their understanding of the pattern differs from mine.

My question is: If we have a data that we would like to reuse in other views, can we store them as properties in a repository (seeing as the repository pattern is a singleton) and access them from other viewmodels?

Here's a generic example of what I mean:

object AnimalRepository {
       val favoriteBreed : Breed? = null
}

and we would access it like so:

class DogViewModel(
    application: Application
) : AndroidViewModel(application){

    val animalRepository = AnimalRepository 

fun setFavoriteBreed(favBreed: Breed) {
    animalRepository.favoriteBreed = favBreed
}

fun getFavoriteBreed() : Breed {
    return animalRepository.favoriteBreed
}

In this case, i did not make use of LiveData for simplicity purposes.

The debate arose from our different interpretations of this section of Android's guide to app architecture: https://developer.android.com/jetpack/docs/guide#truth

redouane
  • 127
  • 1
  • 9

1 Answers1

0

This is how personally I would use a Repository for and also it is how the repository can be used. Repository is the place where we have data coming from. So that makes it easy for any view or the activity to access the data from directly the Repository and can be used from any ViewModel. Does this answer your question or you need more details?

Nitin Tej
  • 353
  • 1
  • 7
  • Thanks for you input. Do you have a public repo with a working example of this approach? Thanks – redouane Jun 05 '20 at 13:19
  • Sure, I have a small project of mine that I have used this pattern. Here it is in GitLab.https://gitlab.com/mountblue/cohort-12-android/major-projects/meetupclone.git please don't mind the naming convention though. – Nitin Tej Jun 05 '20 at 14:07
  • Thanks but i'm pretty sure it's private, it's asking me to authenticate – redouane Jun 05 '20 at 15:03
  • you can check out this open-source project.https://github.com/MindorksOpenSource/MVVM-Architecture-Android-Beginners – Nitin Tej Jun 05 '20 at 16:25
  • You must've misunderstood me, because this is no way the approach I was talking about since in this example, no property is stocked within the repository – redouane Jun 05 '20 at 17:30
  • i thought you were using a standard way of using MVVM architecture. There are allot more examples in meduim where they show sample apps. – Nitin Tej Jun 05 '20 at 17:47