【问题标题】:Combine a Flow and a non Flow api response Kotlin结合一个 Flow 和一个非 Flow api 响应 Kotlin
【发布时间】:2022-01-09 13:07:34
【问题描述】:

我目前有一个逻辑如下:

interface anotherRepository {
      fun getThings():  Flow<List<String>>
}
interface repository {
    suspend fun getSomeThings(): AsyncResult<SomeThings>
}
when (val result = repository.getSomeThings()) {
            is AsyncResult.Success -> {
                anotherRepository.getThings().collectLatest {
                    // update the state
                }
                else -> { }
            }
        }

我遇到的问题是,如果repository.getSomeThings 之前已被多次触发,anotherRepository.getThings 将被触发来自repository.getSomeThings 的所有预加载值的数量。我想知道使用这些存储库的正确方法是什么,一个是挂起功能,另一个是一起流。 Rx 中的 combineLatest{} 等效行为。

谢谢。

【问题讨论】:

  • 你能解释一下你想要发生的事情吗?你想要一个基于getThings() 的流,它将getThings() 的每个值与getSomeThings() 的当前值结合起来吗?
  • 感谢 Joffrey 的回复,我想要的是,每次 getThings 流发出时,我都想将它与挂起乐趣 getSomeThings() 加载的任何最后一个值配对这有帮助吗?
  • getSomeThings() 的最后一个值是什么意思?此函数不会发出新值,只要您要求它执行此操作,它就会返回一个值。是否要重复执行此函数以获取新值?
  • getSomeThings() 当然会在触发时发出。但是我看到的是collectLatest lambda 每次getThings 发出时都会被触发多次。与 getSomeThings() 不同的值(之前加载的值)
  • 基本上我需要两个不同类型的 combineLatest。异步结果 + 流。

标签: kotlin kotlin-coroutines kotlin-flow


【解决方案1】:

有几种方法可以解决您的问题。一种方法就是打电话 repository.getSomeThings() 中的 collectLatest 块和缓存最后的结果:

var lastResult: AsyncResult<SomeThings>? = null

anotherRepository.getThings().collectLatest {
    if (lastResult == null) {
        lastResult = repository.getSomeThings()
    }
    // use lastResult and List<String>
}

另一种方法是创建一个Flow,它将调用repository.getSomeThings() 函数和combine 两个Flow:

combine(
  anotherRepository.getThings(),
  flow {emit(repository.getSomeThings())}
) { result1: List<String>, result2: AsyncResult<SomeThings>  ->
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 2022-12-15
    • 2020-03-12
    • 2011-11-01
    相关资源
    最近更新 更多