首页 > 解决方案 > RxJava / RxKotlin - 如果上一步失败,andThen 仍然执行。如何停止?

问题描述

我是 RxJava 新手,在处理错误情况时遇到了困难。该应用程序在 Kotlin 中,但它可能不会有太大的不同。该场景基本上是用户身份验证,然后执行操作,但如果用户未获得授权/具有错误的身份验证令牌,我会生成异常并希望停止处理。现在我有我的检查令牌的功能,它看起来像这样。

fun checkAuthority(authToken: AuthToken, requiredAuthority: Authority): Completable =
    authorityRepository.getAuthorities(authToken)
        .filter { it == requiredAuthority }
        .switchIfEmpty { subscriber -> subscriber.onError(UnauthorizedException("must have '$requiredAuthority' authority")) }
        .ignoreElements()

然后我有一个看起来有点像这样的函数,它检查权限,然后如果他们被授权,应该做一个操作。

fun create(model: EntityCreate, authToken: AuthToken): Single<Entity> =
    checkAuthority(authToken, CAN_WRITE_ENTITY)
        .andThen(entityRepository.insert(model, OffsetDateTime.now(clock)))

我想要的是,如果生成 UnauthorizedException 不执行 andThen。

也许我对文档的理解存在差距,但例如我尝试将doOnErrorThrowable 放在andThen. onErrorComplete我在同一个地方试过。无论我做什么,andThen最终都会执行。

如果该行执行,该模式会如何放弃Completablesubscriber.onError

标签: kotlinrx-java2rx-kotlin2

解决方案


推荐阅读