0

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)); 
                    }
                });
    }

a3dsfcv
  • 1,146
  • 2
  • 20
  • 35

2 Answers2

1
Mono<Void> insertUnique(Student student) {
  getStudentsBySomething()
    .collectList()
    .flatMap(students -> {
      if(students.isEmpty()) {
        return insert(student);
      } else {
        throw new RuntimeException(e);
      }
    };
}
Ilya Zinkovich
  • 4,082
  • 4
  • 25
  • 43
1

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();
                    }
                });
    }
Erik Finnman
  • 1,459
  • 18
  • 25