PhilBlais
PhilBlais

Reputation: 1186

Is it best practice MVVM to use one repository for multiple Dao?

I'm trying to build an Android app using the MVVM design pattern. I currently have 3 types of Dao created (Dao1, Dao2, Dao3) for 3 different types of PostTypes, using Realm as the database. My 3 Daos look similar but contain Object with some identical variables, but with many different ones as well.

class Dao1(db: Realm) : Dao<PostType1>(db) {

    fun findAllAsync(): LiveData<RealmResults< PostType1 >> {
        return RealmResultsLiveData(where().findAllAsync())
    }

    fun findById(id: Int): LiveData< PostType1 >? {
        return RealmLiveData(where().equalTo("id", id).findFirst())
    }

    private fun where(): RealmQuery<CTDCastaway> {
        return db.where(PostType1::class.java)
    }
}

I'm trying to figure out if I should be creating a repository for each Dao or 1 to rule them all.

class PostRepositary private constructor(val postsDao1: Dao1?){
    fun getDao1Posts() = postsDao1?.findAllAsync()
    fun getDao1PostById(entityId: Int) = postsDao1?.getById(entityId)

    companion object{
        @Volatile private var instance:PostRepositary? = null
        fun getWildlifeInstance(postsDao1: Dao1) =
            instance ?: synchronized(this){
                instance ?: PostRepositary(postsDao1).also { 
                instance = it 
             }
        }
    }
}

So should I create 1 repository for each of my Post types or 1 repository for all 3 Post types considering they share some common properties?

And how would I go about creating a single repository for multiple Daos?

Any links to documentation related to this would be appreciated.

Upvotes: 2

Views: 993

Answers (1)

martinseal1987
martinseal1987

Reputation: 2428

example of two daos one repository

public class CardRepositoryDummy {

private final CardDao cardDao;
private final UserDao userDao;
private LiveData<List<Card>> cardListLiveData;
private DbHelper db;
private int keystage;
private static final String TAG = "CardRepo";

public CardRepositoryDummy(Application application) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(application);
    keystage = sharedPreferences.getInt(Constants.SHARED_PREF_CARD_KEYSTAGE,0);
    db = DatabaseBuilder.getDatabase(application);
    cardDao = db.cardDaoLive();
    userDao = db.userDao();
}

public CardRepositoryDummy(Context application) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(application);
    keystage = sharedPreferences.getInt(Constants.SHARED_PREF_CARD_KEYSTAGE,0);
    db = DatabaseBuilder.getDatabase(application);
    cardDao = db.cardDaoLive();
    userDao = db.userDao();
}

Upvotes: 1

Related Questions