使用来自另一个可观察对象的数据
Using data from another observable
我没有融入 ReactiveX 思维模式,或者我正在使用的代码库编写得不好。
假设我有一些 Observable A() 并且我需要来自另一个 Observable B() 的数据以便对来自 A 的数据进行验证,我如何在 RxJava 中完成此操作(更喜欢 RxKotlin 实现)。请注意,A 和 B return 都是对象列表中的一个。
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 等
所以你可以使用.map {}
运算符:
fun A() : Single<List<Foo>> {
return B.getAll().map { allFromB ->
val record = readRecords()
if (allFromB.contains(record)) {
// ... some validation
}
...
}
}
更新
如果你几乎没有这样的 Observables,你需要使用 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>
}
}
我没有融入 ReactiveX 思维模式,或者我正在使用的代码库编写得不好。
假设我有一些 Observable A() 并且我需要来自另一个 Observable B() 的数据以便对来自 A 的数据进行验证,我如何在 RxJava 中完成此操作(更喜欢 RxKotlin 实现)。请注意,A 和 B return 都是对象列表中的一个。
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 等
所以你可以使用.map {}
运算符:
fun A() : Single<List<Foo>> {
return B.getAll().map { allFromB ->
val record = readRecords()
if (allFromB.contains(record)) {
// ... some validation
}
...
}
}
更新
如果你几乎没有这样的 Observables,你需要使用 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>
}
}