I am currently applying Room
+ ViewModel
+ LiveData
to my project.
In my app, there is "obviously" observe data that is needed, but not all.
The code below is example code for category
data. In my situation, category data does not change and always maintains the same value state (13 categories and content does not change). Categories are data that is loaded from the Database through the CategoryItemDao
class.
Does category data need to be wrapped with livedata?
Or is there a reason enough to use LiveData in addition to its observerable
feature?
I've read the guide to LiveData several times, but I do not understand the exact concept.
CategoryItemDao
@Dao
interface CategoryItemDao {
@Query("SELECT * FROM CategoryItem")
fun getAllCategoryItems(): LiveData<MutableList<CategoryItem>>
}
CategoryRepository
class CategoryRepository(application: Application) {
private val categoryItemDao: CategoryItemDao
private val allCategories: LiveData<MutableList<CategoryItem>>
init {
val db = AppDatabase.getDatabase(application)
categoryItemDao = db.categoryItemDao()
allCategories = categoryItemDao.getAllCategoryItems()
}
fun getAllCategories() = allCategories
}
CategoryViewModel
class CategoryViewModel(application: Application) : AndroidViewModel(application) {
private val repository = CategoryRepository(application)
private val allCategories: LiveData<MutableList<CategoryItem>>
init {
allCategories = repository.getAllCategories()
}
fun getAllCategories() = allCategories
}