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