RxJava filter can be observed with other observables

I am using RxAndroid 2.0.1 with RxJava 2.0.6.

I have two observables: one returns Maybe<MyObject>based on some String (ID). When an additional object is returned, I must call the second, which takes an instance of MyObject, and returns Single<Boolean>if the object satisfies some conditions. Then I can perform some additional operations on 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 am wondering how I can simplify my code. My ideas:

  • Try using zip- I cannot, because the second Observable cannot be signed until the first returns MyObject

  • filter - , , . , :

    objectDAO.getById(objectId)
      .filter(myObject ->
        otherDAO.checkCondition(myObject).blockingGet()
      )
      .subscribe(
          myObject -> checkCondition(myObject),
          throwable -> /* Fallback */,
          () -> /* Fallback */
      );
    
  • flatMap - Boolean, . - blockingGet Maybe.empty()

, , "" ( , , )?

+4
3

, :

objectDAO.getById(objectId)
    .flatMapSingle(myObject -> otherDAO
        .checkCondition(myObject)
        .map(isTrue -> Pair.create(myObject, isTrue))
    )

Observable<Pair<MyObject, Boolean>> , : subscribe Boolean , filter ..

+3

RxJava2Extensions akarnokd filterAsync ( compose), , Publisher<Boolean>;)

0

, , , - . , objectDAO.getById(objectId) Observable<T> otherDAO.checkCondition(myObject) Single<Boolean>, :

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

Observable.empty , , , .flatMapSingle(obj ->...)

, (, , ):

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

Source: https://habr.com/ru/post/1672921/


All Articles