是否有处理RxJava空案例的简洁方法?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (201)

我试过以下方法:

fun <T> Maybe<T>.subscribeWithEmptyHandler(onSuccess: (T) -> Unit, onError: (Throwable) -> Unit, onEmpty: () -> Unit) {
    this.isEmpty.subscribe({ if (it) onEmpty() }, { onError(it) })
    this.subscribe({ onSuccess(it) }, { onError(it) })
}

运行:

Maybe.create<Int> {
    println("subscribing")
    //Remove line below to create Empty Maybe
    it.onSuccess(5)
    it.onComplete()
}
    .subscribeWithEmptyHandler({println("success")},{println("error")},{println("empty")})

有没有什么简便方法?

提问于
用户回答回答于

使用Maybe.doOnEvent(Java示例):

Maybe
 .empty()
 .doOnEvent((value, error)-> {
    if (value==null && error == null) {
      System.out.println("empty!");
    }})
 .subscribe();
用户回答回答于

试试以下简便方法:

fun <T> Maybe<T>.subscribeWithEmptyHandler(onSuccess: (T) -> Unit, onError: (Throwable) -> Unit, onEmpty: () -> Unit) {
    this.toSingle()
        .subscribe(
            { onSuccess(it) },
            { if (it is NoSuchElementException) onEmpty() else onError(it) }
        )
}

扫码关注云+社区

领取腾讯云代金券