I'm trying to apply clean-architecture approach to my project (Link: guide I'm currently referencing).
我正在使用Room数据库进行本地存储,我希望它成为应用程序中的单一数据源——这意味着从网络通话中收集的所有数据首先保存在数据库中,然后才传递给演示者.Room提供了从DAO返回LiveData的功能,这正是我需要的.
However I also want to use repositories as a single way to access data. Here's an example of repository interface in domain layer (the most abstract one):
interface Repository<T>{
fun findByUsername(username: String) : List<T>
fun add(entity: T): Long
fun remove(entity: T)
fun update(entity: T) : Int
}
现在我遇到了问题-我需要在我的ViewModel中从Room的DAO中获取LiveData,并且我希望使用Repository实现来获取它.但要做到这一点,我需要:
- Change Repository method findByUsername to return LiveData>
- Or call Room's DAO directly from ViewModel skipping repository implementation completely
Both of these options have sufficient drawbacks:
- 如果我将
android.arch.lifecycle.LiveData
导入到我的存储库界面,它将打破域层的抽象,因为它现在依赖于android架构库. - If I call Room's DAO directly in the ViewModel as
val entities: LiveData<List<Entity>> = database.entityDao.findByUsername(username)
then I'm breaking the rule that all data access must be made using Reposiotry and I will need to create some boilerplate code for synchronization with remote storage etc.
How is it possible to achieve single data source approach using LiveData, Room's DAO and Clean architecure patterns?