Search code examples
rx-javareactive-programmingrx-androidgreendao

RxJava combine with boolean operators


I have two Observables. observableDisconnectContact is responsible to call API request for remove contact and it works properly. Second one observableDeleteContact emits true or false if contact was removed from database. I use greeDao.

Observable<Boolean> observableDisconnectContact = apiClient.observableDisconnectContact(contactModel.getId()) 

Observable<Boolean> observableDeleteContact = contactModelRxDao.deleteByKey(contactModel.getDbId())

I want combine both but second observable should start when first is done and return true. I think about use concat() and first(). But I have to know that both of stream emits result is true. So I use combineLatest() or zip(). But it is not good idea becuase both streams are running in the same time. I noticed that first() operator doesn't work for zip() and combineLatest().

How can I combine both Observables where second started after first stream is or not if first return false and result of both streams should be as one result.

Observable.combineLatest(observableDisconnectContact, observableDeleteContact, new Func2<Boolean, Boolean, Boolean>() {
            @Override
            public Boolean call(Boolean isDisconnectSuccess, Boolean isRemoveSuccess) {
                return isDisconnectSuccess && isRemoveFromDatabaseSuccess;
            }
        }).subscribe(new Subscriber<Boolean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Boolean isDeleted) {
                if (isDeleted) {
                    //TODO
                }
            }
        });

Solution

  • observableDisconnectContact
            .flatMap(isDisconnectSuccessful -> {
                if(isDisconnectSuccessful) return observableDeleteContact;
                else return Observable.just(false);
             })
             .subscribe(isBothActionsSuccessful -> {
                 if(isBothActionsSuccessful) {
                     //success!
                 } else {
                     //something goes wrong
                 }
             });