3
RxJava 2

我有以下内容,我订阅了 2 个 observables,它工作正常。我不认为这是最好的方法。

getSalesInfo如果第一个getProductDetails满足条件,我只想订阅第二个。这只是我正在尝试做的一个示例。如果条件不满足,则不会发生任何事情。

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)

我发现的另一种选择是使用flatmap它将返回第二个SaleInfoobservable。我必须在看起来不正确的 else 条件下返回一个空的 Observable。有没有更好的办法?

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

非常感谢您的任何建议

4

1 回答 1

2

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.

于 2020-03-12T17:56:16.823 回答