Vous pouvez utiliser la fonction hasElement()
en mode Mono. Jetez un oeil à cette fonction d'extension Mono:
inline fun <T> Mono<T>.errorIfEmpty(crossinline onError:() -> Throwable): Mono<T> {
return this.hasElement()
.flatMap { if (it) this else Mono.error(onError()) }
}
inline fun <T> Mono<T>.errorIfNotEmpty(crossinline onError: (T) -> Throwable): Mono<T> {
return this.hasElement()
.flatMap { if (it) Mono.error(onError.invoke(this.block()!!)) else this }
}
Le problème avec switchIfEmpty
est qu'il évalue toujours l'expression passée dans l'argumentation - écrit ce code produira toujours objet Foo:
mono.switchIfEmpty(Foo())
Vous pouvez écrire votre propre extension à l'expression d'évaluation paresseuse passée en argument:
inline fun <T> Mono<T>.switchIfEmpty(crossinline default:() -> Mono<T>): Mono<T> {
return this.hasElement()
.flatMap { if (it) this else default() }
}
Voici deux autres fonctions d'extension - vous pouvez les utiliser pour vérifier si er mot de passe est correct:
inline fun <T> Mono<T>.errorIf(crossinline predicate: (T) -> Boolean, crossinline throwable: (T) -> Throwable): Mono<T> {
return this.flatMap { if (predicate(it)) Mono.error(throwable(it)) else Mono.just(it) }
}
inline fun <T> Mono<T>.errorIfNot(crossinline predicate: (T) -> Boolean, crossinline throwable: (T) -> Throwable): Mono<T> {
return this.errorIf(predicate = { !predicate(it) }, throwable = throwable)
}
Vous devez expliquer ce que votre problème est – s1m0nw1
@ s1m0nw1 je veux factoriser ce style réactif – maystrovyy