【问题标题】:How to avoid .subscribe in subscribe in RxJava如何避免 .subscribe 在 RxJava 中订阅
【发布时间】:2021-07-04 01:32:58
【问题描述】:

我有一个使用 Rxjava 的代码 sn-p,并且我使用订阅内的订阅来编写它。如何使用地图或平面地图的唯一订阅?

amount.textChanges.observable.map {
        when {
            (it.isNotEmpty() && it.toBigDecimal() > BigDecimal(1500)) -> showDialog(R.string.max_amount_error)
            (it.isNotEmpty() && it.toBigDecimal() > BigDecimal.ZERO) -> {
                getCommissionUseCase.execute(it.toInt() * 100).subscribe { payment ->
                    commission.accept((payment.data.toDouble() / 100).toString())
                }.untilDestroy()
            }
            (it.isEmpty()) -> nextBtnEnabled.consumer.accept(false)
        }
    }.subscribe()

【问题讨论】:

    标签: android kotlin subscribe flatmap


    【解决方案1】:
    amount.textChanges.observable
      .flatMapCompletable {
        when {
          (it.isNotEmpty() && it.toBigDecimal() > BigDecimal(1500)) -> Completable.fromAction { showDialog(R.string.max_amount_error) }
          (it.isNotEmpty() && it.toBigDecimal() > BigDecimal.ZERO) -> getCommissionUseCase.execute(it.toInt() * 100)
             .doOnSuccess { payment ->
               commission.accept((payment.data.toDouble() / 100).toString())
             }
             .ignoreElement()
          (it.isEmpty()) -> Completable.fromAction { nextBtnEnabled.consumer.accept(false) }
        }
      }.subscribe()
    

    如果您使用的是Observable,则可以使用doOnNext、ignoreElements,而不是doOnSuccess、ignoreElement,后者仅适用于Single

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 2023-01-11
      • 1970-01-01
      • 2023-01-30
      • 2023-03-23
      相关资源
      最近更新 更多