Android Repository 解决多数据源问题

更新日期: 2021-02-05 阅读次数: 4452 字数: 486 分类: Android

在看 Android Room 时,不能理解的是,既然有了 Dao 层,为何还要再加上一层 Repository 的封装。

看了一下 Google 官方对 Android Repository 的介绍:

https://developer.android.com/codelabs/android-room-with-a-view-kotlin#8

概括来说

Repository 解决了多少数据源的问题。即一个 App 的数据来源可以是:

  • 本地 SQLite 数据库。使用 Dao 访问。
  • 远端服务器。使用 HTTP API 接口访问。

Repository 将这两种情况进行封装,让你可以使用统一的方式进行数据拉取。

是代码规范,而不是组件

Repository 只是一个代码规范,或者最佳实践指导;而不是内置组件。 方便代码组织结构更清晰。

啰嗦

对我来说,这更多的是一种困扰。我并没有感觉到任何的方便之处。。。

但是,对于另一个示例中

https://github.com/android/architecture-components-samples/blob/master/BasicSample/app/src/main/java/com/example/android/persistence/DataRepository.java

将所有的 Dao 都放到一个 Repository 中进行封装,我倒是觉得方便了一点。

相比之下,每个 Dao 对应一个 Repository 我觉得就是啰嗦了。

截然不同的实现方式

官方 demo sunflower 与 Repository 示例中的实现,截然不同,我完全不知道该参考哪个更好。。。

sunflower:

@Singleton
class PlantRepository @Inject constructor(private val plantDao: PlantDao) {

    fun getPlants() = plantDao.getPlants()

    fun getPlant(plantId: String) = plantDao.getPlant(plantId)

    fun getPlantsWithGrowZoneNumber(growZoneNumber: Int) =
        plantDao.getPlantsWithGrowZoneNumber(growZoneNumber)
}

Repository 示例:

// Declares the DAO as a private property in the constructor. Pass in the DAO
// instead of the whole database, because you only need access to the DAO
class WordRepository(private val wordDao: WordDao) {

    // Room executes all queries on a separate thread.
    // Observed Flow will notify the observer when the data has changed.
    val allWords: Flow<List<Word>> = wordDao.getAlphabetizedWords()

    // By default Room runs suspend queries off the main thread, therefore, we don't need to
    // implement anything else to ensure we're not doing long running database work
    // off the main thread.
    @Suppress("RedundantSuspendModifier")
    @WorkerThread
    suspend fun insert(word: Word) {
        wordDao.insert(word)
    }
}

不使用 Repository 直接操作数据库如何

// TODO

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式