Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

project reactor - Using reactive java, insert element only if flux is empty

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perhaps something like this? Then you don't have to collect the entire Flux which might be bad if there are a lot of items:

 Mono<Void> insertUnique(Student student) {
        return getStudentsBySomething("test")
                .hasElements()
                .flatMap(hasStudents -> {
                    if (!hasStudents) {
                        return insert(student);
                    } else {
                        throw new RuntimeException();
                    }
                });
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...