RxJava: Complete stream based on condition

Viewed 1002

I have on Observable, which emits items when some data is coming from a BLE connection:

public interface CommunicationController {
     Flowable<DataContainer> dataReceived();
}

On top of this I want to build a Observable, which completes when one of the following conditions is true:

a. I receive two messages of a specific type (this is done by using filter operator on the received DataContainer item.

communicationController.dataReceived()
    .filter(data -> isTypeA(data) || isTypeB(data))
    .take(2)
    .toList()
    .map(dataContainers -> doSomeMappingToCommon object) 

b. I receive one message of a specific type (again using filter operator).

communicationController.dataReceived()
    .filter(data -> isTypeC(data))
    .firstOrError()
    .map(dataContainers -> doSomeMappingToCommon object); 

How can I combine those two Observables into a single one? Additionally only one of the two Observables will emit an item.

2 Answers

To combine 2 observables, you can use operator zipWith. Example:

Observable<AppMetaDataBiz> appMetaDataObservable = this.mAppRepository.getAppMetaData();

Observable<ProductBiz> productDetailsObservable =
        this.mProductRepository.getProductDetails(this.productId);

return productDetailsObservable.zipWith(appMetaDataObservable,
                                            ((jmProduct, jmAppMetaData) -> {

                                               //TODO: implement business logic

                                                return jmProduct;
                                            }));
Related