ant2009
ant2009

Reputation: 22666

Subscribing to 2 observables but only subscribe to the second one if a condition is true for the first one

RxJava 2

I have the following where I am subscribing to 2 observables it works ok. I don't think its the best way.

I only want to subscribe to the second one getSalesInfo if the first one getProductDetails meets a condition. This is just a sample of what I am trying to do. If the condition is not met then nothing more will happen.

fun main(args: Array<String>) {
    getProductDetails()
            .subscribeBy { productDetails ->
                if (productDetails.productID == 1234) {
                    getSalesInfo().subscribeBy {
                        getSalesInfo()
                                .subscribeBy { saleInfo ->
                                    println(saleInfo.salesReference)
                                }
                    }
                }
            }
}

fun getProductDetails(): Observable<ProductDetails> =
        Observable.just(ProductDetails(1234, "Product One"))

fun getSalesInfo(): Observable<SaleInfo> =
        Observable.just(SaleInfo("Sales Reference 1"))

data class ProductDetails(val productID: Int,
                          val productDescription: String)

data class SaleInfo(val salesReference: String)

Another alternative I have found is using flatmap that will return the second SaleInfo observable. I have to return a empty Observable in the else condition which doesn't look right. Is there a better way?

getProductDetails()
            .flatMap { productDetails: ProductDetails ->
                if (productDetails.productID == 1234) {
                    getSalesInfo()
                }
                else {
                    Observable.empty()
                }
            }
            .subscribeBy { saleInfo ->
                println("Using flatmap ${saleInfo.salesReference}")
            }

Many thanks for any suggestions

Upvotes: 3

Views: 177

Answers (1)

Hack5
Hack5

Reputation: 3601

I would suggest that your first method is better. It describes exactly what you want it to do, and has the benefit that if you wanted to take some action when productID != 1234, you can have a different callback for the RX action that is taken. While they do essentially the same thing, there is probably a slight overhead for the second one due to the flatMap, and it also reduces flexibility.

Upvotes: 2

Related Questions