【问题标题】:Using data from another observable使用来自另一个 observable 的数据
【发布时间】:2023-03-19 19:31:01
【问题描述】:

我无法进入 ReactiveX 思维模式,或者我正在使用的代码库写得不好。

假设我有一些 Observable A() 并且我需要来自另一个 Observable B() 的数据以便对来自 A 的数据进行验证,我如何在 RxJava 中完成此操作(更喜欢 RxKotlin 实现)。请注意,A 和 B 都返回对象列表的 Single。

fun B(): Single<List<Bar>> {
  ...
}

fun A() : Single<List<Foo>> {
  Single.just(readRecords()).map { record ->
    // val bar = B.getAll()??? This seems like an anti-pattern and I'm not sure if it would necessarily be right to .subscribe()???

    if (bar.contains(record)) {
      // ... some validation
    }
  }
}

更新 1:应该强调验证需要多个来源,因此您可以拥有 B、C、D 等。

【问题讨论】:

    标签: rx-java rx-kotlin


    【解决方案1】:

    所以你可以使用.map {} 运算符:

    fun A() : Single<List<Foo>> {
        return B.getAll().map { allFromB ->  
            val record = readRecords()
            if (allFromB.contains(record)) {
               // ... some validation
            }
            ...
        }
    }
    

    更新 如果你的 Observable 很少,你需要使用 Observables.combineLatest()Observable.combineLatest()(取决于你使用的 RX 版本):

    fun B(): Single<List<BarB>> {
       ...
    }
    
    fun C(): Single<List<BarC>> {
       ...
    }
    
    fun D(): Single<List<BarD>> {
       ...
    }
    
    fun A() : Single<List<Foo>> {
        return Observable.combineLatest(B.getAll(), C.getAll(), D.getAll) { barB, barC, barD -> 
                val record = readRecords()
                //Do your staff here with all this vals and return List<Foo>
            }
    }
    

    【讨论】:

    • 我应该更新这个问题。如果您有 2 个或更多您需要的这些来源(例如 B、C、D...),会发生什么?将一堆 .map 链接在一起似乎很奇怪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2022-11-12
    • 2019-01-23
    相关资源
    最近更新 更多