You can use hasElement()
function in Mono. Take a look at this extension functions to 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 }
}
The problem with switchIfEmpty
is that it always evaluate expression passed in argument - writing such code will always produce Foo object:
mono.switchIfEmpty(Foo())
You can write your own extension to lazy evaluate expression passed in argument:
inline fun <T> Mono<T>.switchIfEmpty(crossinline default: () -> Mono<T>): Mono<T> {
return this.hasElement()
.flatMap { if (it) this else default() }
}
Here are two more extension functions - you can use them to check whether password is 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)
}