用其他 Observable 过滤 RxJava Observable [英] Filter RxJava Observable with other Observable
问题描述
我使用 RxAndroid 2.0.1 和 RxJava 2.0.6.
I'm using RxAndroid 2.0.1 with RxJava 2.0.6.
我有两个可观察对象:一个基于某个字符串 (ID) 返回 Maybe
.当返回可选对象时,我必须调用第二个接受 MyObject 实例并在对象满足某些条件时返回 Single
的对象.然后我可以对对象实例做一些进一步的操作.
I have two observables: one returns Maybe<MyObject>
based on some String (ID). When the optional object is returned, I have to call the second one that takes the MyObject instance and returns Single<Boolean>
if object meets some conditions. Then I can do some further operations with the object instance.
我目前的实现如下:
objectDAO.getById(objectId)
.subscribe(
myObject -> checkCondition(myObject),
throwable -> /* Fallback */,
() -> /* Fallback */
);
private void checkCondition(final MyObject myObject) {
otherDAO.checkCondition(myObject)
.subscribe(
isTrue -> {
if (isTrue) {
// yay! now I can do what I need with myObject instance
} else {
/* Fallback */
}
},
throwable -> /* Fallback */
);
}
现在我想知道如何简化我的代码.我的想法:
Now I'm wondering how could I simplify my code. My ideas:
尝试使用
zip
- 我不能,因为在第一个返回 MyObject 之前无法订阅第二个 Observable
Try to use
zip
- I can't because second Observable can't be subscribed until the first one returns the MyObject
尝试使用 filter
- 现在的问题是我需要使用阻塞 get 来调用第二个 observable.它可能会工作,但看起来像代码异味:
Try to use filter
- Now the issue is that I need to use blocking get to call second observable. It will propably work, but looks like a code smell:
objectDAO.getById(objectId)
.filter(myObject ->
otherDAO.checkCondition(myObject).blockingGet()
)
.subscribe(
myObject -> checkCondition(myObject),
throwable -> /* Fallback */,
() -> /* Fallback */
);
尝试使用 flatMap
- 第二个 observable 返回布尔值,而我需要返回原始对象.因此,我需要使用 blockingGet
映射代码片段并返回原始对象或 Maybe.empty()
Try to use flatMap
- The second observable returns Boolean while I need to return the original object. Because of that I need to mape a code snippet with blockingGet
and return original object or Maybe.empty()
有什么建议可以让代码干净"(它更小,但仍然清楚内部发生的事情)吗?
Any suggestions how to do it in such a way that the code is "clean" (it's smaller and it's still clear what's happening inside)?
推荐答案
你可以做的一件事:
objectDAO.getById(objectId)
.flatMapSingle(myObject -> otherDAO
.checkCondition(myObject)
.map(isTrue -> Pair.create(myObject, isTrue))
)
然后你有一个 Observable
并且可以按照你想要的方式继续:subscribe
直接并检查 Boolean
在那里,filter
通过布尔值等
Then you have an Observable<Pair<MyObject, Boolean>>
and can proceed however you want: subscribe
directly and check the Boolean
there, filter
by the Boolean value, etc.
这篇关于用其他 Observable 过滤 RxJava Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!