I'm new to RxJava and am having a hard time with handling error cases. The application is in Kotlin but it probably won't make much of a difference. The scenario is basically user authentication and then performing an action but if the user is not authorized/has a bad auth token I generate an exception and want to cease processing. Right now I have my function that checks tokens and it looks like this.
fun checkAuthority(authToken: AuthToken, requiredAuthority: Authority): Completable =
authorityRepository.getAuthorities(authToken)
.filter { it == requiredAuthority }
.switchIfEmpty { subscriber -> subscriber.onError(UnauthorizedException("must have '$requiredAuthority' authority")) }
.ignoreElements()
Then I have a function that looks a bit like this that checks permissions then is supposed to do an operation if they are authorized.
fun create(model: EntityCreate, authToken: AuthToken): Single<Entity> =
checkAuthority(authToken, CAN_WRITE_ENTITY)
.andThen(entityRepository.insert(model, OffsetDateTime.now(clock)))
What I want is that if the UnauthorizedException is generated to not execute the andThen.
Perhaps there is a gap in my understanding of the documentation but I've for instance tried putting doOnError
to throw the Throwable before the andThen
. I've tried onErrorComplete
in the same place. No matter what I do the andThen
eventually executes.
What would the pattern look like to abandon the Completable
chain should the subscriber.onError
line executes?