将 Room DAO 流程与手动网络请求合并为一个流程

问题描述 投票:0回答:0

在我的存储库中,我目前有两种方法:

// watched by my viewModel, but this Flow lacks the information about
// failed network requests from getLatestItemsFromNetwork()
suspend fun getCachedItems() : Flow<Result<List<Item>>> {
    // Returns Result.cacheUpdate
    return Result.cacheUpdate(itemDao.items()) // itemDao is a Room DAO Flow
}

// triggered when user clicks refresh button / swipe to refresh.
// note that this is not a Flow.
suspend fun getLatestItemsFromNetwork(): Result<List<Item>> {
    // Returns Result.success or Result.error
    return remoteSource.getItems()
}

看看这两种方法,我有三种可能的输出:

  1. Result.cacheUpdate
  2. 结果.成功
  3. 结果.error

我现在想创建一个方法

fun getItemUpdates: Flow<Result<List<Item>>> 

在我的存储库中可以输出这三个结果,例如通知缓存更新以及网络结果。我不知道该怎么做,因为我必须以某种方式将 Flow(来自

getCachedItems()
的那个)与
getLatestItemsFromNetwork()
结合起来,这不是 Flow。有什么想法吗?

提示:在

getLatestItemsFromNetwork()
中成功更新缓存(项目表)(这将触发对
getCachedItems()
的流程的更新)不是我需要的解决方案。这会丢失有关失败的网络请求的信息,我需要在 UI 中显示错误消息!

kotlin repository kotlin-flow flow
© www.soinside.com 2019 - 2024. All rights reserved.