I have a db, where I want to see my entry with the unique key. But sometimes I need to allow duplicates for that key, so I can not use indexes.
I have something like this
Flux<Student> getStudentsBySomething(String something) {..}
Mono<Void> insert(Student student) {...}
Mono<Void> insertUnique(Student student) {
// I want to write something like
if (getStudentsBySomething().isEmpty()) {
insert(student);
} else{
throw new RuntimeException(e);
}
}
but I'm really stuck on how to rewrite insertUnique
with reactive code
Update 1:
Just came up with the following solution. I wonder if can it be done in a better way
Mono<Void> insertUnique(Student student) {
return getStudentsBySomething(student.getSomething())
.count()
.flatMap(records -> {
if (records == 0) {
return insert(student);
} else {
return Mono.error(alreadyExist(student));
}
});
}
question from:
https://stackoverflow.com/questions/65938491/using-reactive-java-insert-element-only-if-flux-is-empty 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…