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实现来获取它.但要做到这一点,我需要:

  1. Change Repository method findByUsername to return LiveData>
  2. Or call Room's DAO directly from ViewModel skipping repository implementation completely

Both of these options have sufficient drawbacks:

  1. 如果我将android.arch.lifecycle.LiveData导入到我的存储库界面,它将打破域层的抽象,因为它现在依赖于android架构库.
  2. 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?

推荐答案

当被问到关于使用RxJava的类似问题时,开发人员通常会回答,这没问题,而且RxJava现在是语言的一部分,所以,您可以在域层使用它.在我看来-如果它对您有帮助,您可以做任何事情,所以,如果使用LiveData不会产生问题-请使用它,或者您可以使用RxJava或Kotlin协程来代替.

Kotlin相关问答推荐

为什么Kotlin函数参数名会 destruct 方法调用?

如何避免使用公共类实现内部接口

处理合成层次 struct 中的深层按钮以切换视图

在Kotlin中的嵌套when语句中,else块是强制性的吗?

在Kotlin lambda的参数中如何指定函数类型?

在 Kotlin 中将两个字节转换为 UIn16

Kotlin SIZE_BYTES

如何访问嵌套在另一个 map 中的 map 中的值(在 kotlin 中)

如何在 Spring Boot 3 中为内部类提供运行时提示

Jetpack Compose 中的连续重组

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

具有多个不同类型来源的 LiveData

AIDL 中的 Parcelize 注释:Incompatible types: Object cannot be converted to MyCustomObject

为什么 Kotlin 扩展运算符在传递原始可变参数时需要 toTypedArray()?

java - 如何将函数作为参数从java传递给kotlin方法?

Kotlin boxed Int 不一样

使用 clear() 删除 EncryptedSharedPreferences 不起作用

在调用Kotlin数据类中的超类构造函数之前访问函数

如何限制kotlin协程的最大并发性

Android studio 4.0 新更新版本说 Kotlin 与这个新版本不兼容