Filter RxJava Observable with other Observable

rxjava filter example
rxjava flatmap
rxjava filter arraylist
rxjava operators
rxjava filter maybe
rxjava first
observable with another observable
rxjava take

I'm using RxAndroid 2.0.1 with RxJava 2.0.6.

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.

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'm wondering how could I simplify my code. My ideas:

  1. Try to use zip - I can't because second Observable can't be subscribed until the first one returns the MyObject

  2. 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 */
      );
    
  3. 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)?

One thing you could 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 proceed however you want: subscribe directly and check the Boolean there, filter by the Boolean value, etc.

Observable depends on other Observable, I have an Observable whose emitted item I need for the next Observable but I can​'t use flatMap() because the method I need to call in the  For this purpose, RxJava offers various filtering capabilities. Let's start looking at the filter method. 2.1. The filter Operator. Simply put, the filter operator filters an Observable making sure that emitted items match specified condition, which comes in the form of a Predicate. Let's see how we can filter only the odd values from those emitted:

The RxJava2Extensions extra project by akarnokd has a filterAsync transformer (to be used with compose) that does just that, using a any Publisher<Boolean> ;)

Filtering Observables in RxJava, If we want to emit only the last element, other then using takeLast(1), we can use last. This filters the Observable, emitting only the last element,  The response comes back as an Observable<Response>. Within the Response object there is a List<HotelAvailability> , and within the HotelAvailability object, there is HotelInfo object. If HotelInfo is null , I want to remove the HotelAvailability from the list.

I've come up with solution without passing Pairs with boolean values, in case anybody will face same problem. For example, if objectDAO.getById(objectId) returns Observable<T> and otherDAO.checkCondition(myObject) returns Single<Boolean>, we can handle filtering in such a way:

objectDAO.getById(objectId)
    .flatMap(myObject -> otherDAO
        .checkCondition(myObject)
        .toObservable()
        .filter(Boolean::booleanValue)
        .map(o -> myObject))
    .flatMapSingle(obj -> ...)

Unwanted objects will be resolved to Observable.empty and thus filtered, so that only needed objects will get to .flatMapSingle(obj -> ...)

Basically, same thing can be achieved with slightly easier to understand structure (though, I've found the first one a bit nicer aesthetically):

objectDAO.getById(objectId)
    .flatMap(myObject -> otherDAO
        .checkCondition(myObject)
        .flatMapObservable(isChecked -> isChecked ? Observable.just(myObject) : Observable.empty()))
        .flatMapSingle(obj -> ...)

Filter operator, emit only those items from an Observable that pass a predicate test The Filter operator filters an Observable by only allowing items through that pass a test that you specify in the form of a RxJava 1․x filter ofType GitHub · Twitter · Others. I think the only thing to make this more readable is not using Observable.of() that just reemits the value and use Observable.from() that iterates the array and emits each value as a separate item. let eventsObservable: Observable<Event> = Observable.from(EVENTS);

Exploring RxJava in Android, This operator only emits an item from an Observable if a particular timespan has passed without it emitting another item. Sample  Observables differs from another in the way they produce the data and the number of emissions each Observable makes. We have to wisely choose the best suited Observable depending on the use case. Let’s say we are expecting an emission from an Observable, but if it produces null, then wrong Observable is used.

Reducing a sequence, Rx and other LINQ code. In this example we will use the Where to filter out all even values produced from a Range sequence. var oddNumbers = Observable. Javadoc: filter(Func1) There is also a specialized form of the Filteroperator in RxGroovy that filters an Observable so that it only emits items of a particular class. ofTypedoes not by default operate on any particular Scheduler. Javadoc: ofType(Class) RxJava 1․x filter ofType.

filter, If you would like to complete an observable when a condition fails, check out takeWhile! ​​ Ultimate RxJS ​​. Examples. Example 1: filter for even numbers. In this article well use the operators map(), filter(), and reduce(). As the data elements flow from the observable to the observer, you can apply one or more operators, transforming each element prior to supplying it to the observer. Each operator takes an observable as an input, performs its action, and returns a new observable as an output:

Comments
  • objectDAO.getById(objectId).flatMap(myObject -> otherDAO.checkCondition(myObject).map(isTrue -> Pair.create(myObject, isTrue)) - 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.
  • @david.mihola it's similar to mine 3rd method, except that now I've realized that I don't need to use blocking get. So rather that returning Pair<Boolean, MyObject I can check the boolean and return Maybe.just(myObject) or Maybe.empty() / Maybe.error() Still not sure if it's a good solution.
  • Also, it seems I can't use objectDAO.flatMap(otherDao.map()) combination, and when I change it to objectDAO.map(otherDao.map()) then the result is Single<Maybe<Pair<Boolean, MyObject>>> which is also not so nice
  • Yeah, sorry - it's called flatMapSingle!
  • Yeah, I also found that I can use flatMapSingle instead. Now I have other issue, but not related to the original question. Please paste your full answer below so I can accept it :)