在<Model2>MVVM+Repostiory+LiveData设置中获取HashMap<Model1,List>?



所以我正在开发这个愚蠢的小应用程序来练习MVVM和存储库模式。我目前有两个模型类。它们是CategorySubCategory,我为其定义了以下数据类:

@Entity(tableName = "categories")
data class Category(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int,
@ColumnInfo(name = "name")
val name: String
) {
}

/**
* One to many Relationship from Category to SubCategory
*/
@Entity(
tableName = "sub_categories", foreignKeys = arrayOf(
ForeignKey(
entity = Category::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("category_id")
)
)
)
data class SubCategory(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int,
@ColumnInfo(name = "name")
val name: String,
@ColumnInfo(name = "category_id")
val categoryId: Int
) {
}

如您所见,我已经对资源进行了建模,因此我们需要传递 categoryId 来获取与类别相关的子类别。

现在我对这个MVVM和LiveData和存储库模式很陌生。

我的问题是我正在使用ExpandableListView来填充"类别"下的子类别,并且它的Adapter需要HashMap<Category, List<SubCategory>才能显示可展开的列表视图。

所以我的问题是如何使用db->dao->repository->viewmodel的方法从我的数据库中获取HashMap<Category, List<SubCategory>,无论adpater去哪里。

我想创建一个单独的存储库,例如CategorySubCategoryRespository我可以执行以下操作无济于事?

class CategorySubCategoryRepository(
private val categoryDao: CategoryDao,
private val subCategoryDao: SubCategoryDao
) {
val allCategoriesSubCategories: LiveData<HashMap<Category, List<SubCategory>>>
get() {
val hashMap: HashMap<Category, List<SubCategory>> = hashMapOf()
for (category in categoryDao.getList()) {
hashMap[category] = subCategoryDao.getSubCategoriesListForCategory(category.id)
}
return hashMap
}
}
}

PS:我想我想尽可能使用LiveData

所以我最终做的是,在我的CategorySubcategoryRepository中,我从CategoryDao构建了哈希图,SubcategoryDao如下:

class CategorySubCategoryRepository(
private val categoryDao: CategoryDao,
private val subCategoryDao: SubCategoryDao
) {
fun getHashMap(): LiveData<HashMap<Category, List<SubCategory>>> {
val data = MutableLiveData<HashMap<Category, List<SubCategory>>>()
val hashMap: HashMap<Category, List<SubCategory>> = hashMapOf()
Executors.newSingleThreadExecutor().execute {
for (category in categoryDao.getList()) {
hashMap[category] = subCategoryDao.getSubCategoriesListForCategory(category.id)
}
}
data.value = hashMap
return data
}
}

然后我在视图模型的init{}块中使用它,例如:

hashMap = categorySubCategoryRepository.getHashMap()

然后我在Fragment的onCreateView中观察到它为:

myViewModel.hashMap.observe(this, Observer {
adapter.setCategoryList(it.keys.toList())
adapter.setCategorySubCategoriesMap(it)
elv_categories.setAdapter(adapter) 
adapter.notifyDataSetChanged()
})

如果这不是正确的做法,请发表评论。我这样做只是为了提高我的技能,很想听听是否有更好的方法来做事,或者我的方法是否完全荒谬。

编辑:

根据@SanlokLee的评论。getHashMap函数已更改为:

fun getHashMap(): LiveData<HashMap<Category, List<SubCategory>>> {
val data = MutableLiveData<HashMap<Category, List<SubCategory>>>()
Executors.newSingleThreadExecutor().execute {
val hashMap: HashMap<Category, List<SubCategory>> = hashMapOf()
for (category in categoryDao.getList()) {
hashMap[category] = subCategoryDao.getSubCategoriesListForCategory(category.id)
}
data.postValue(hashMap)
}
return data
}

最新更新