Filter rxjava observable using other observable
I am using rxandroid 2.0.1 and rxjava 2.0.6
I have two observable: one returns may < MyObject > based on some string (ID). When returning an optional object, I must call the second to obtain the MyObject instance and return single < Boolean > if the object meets some conditions. Then I can use the object instance to do some further operations
My current implementation is as follows:
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 want to know how to simplify my code. My idea:
>Try using zip – I can't, because the second observable can't subscribe until the first one returns MyObject > try using filter – now the problem is that I need to call the second observable with blocking get. It works, but it looks like code smell:
objectDAO.getById(objectId)
.filter(myObject ->
otherDAO.checkCondition(myObject).blockingGet()
)
.subscribe(
myObject -> checkCondition(myObject),
throwable -> /* Fallback */,
() -> /* Fallback */
);
>Try using flatmap - the second observable returns a Boolean value, and I need to return the original object. Therefore, I need to write a code fragment using blockingget and return the original object or maybe. Empty()
How can any suggestion be made in such a way that the code is "clean" (it's smaller and still knows what's going on inside)?
resolvent:
One thing you can do:
objectDAO.getById(objectId)
.flatMapSingle(myObject -> otherDAO
.checkCondition(myObject)
.map(isTrue -> Pair.create(myObject, isTrue))
)
Then you have an observable < < pair < < MyObject, Boolean > > and can continue as needed: Subscribe directly and check Boolean values, filter by Boolean values, etc