I have two classes as below. We are using reactive programming in Java for development. Initially the address field in Student class will be null as Student table does not have it. Now I have to update the address field in Student class based on the addressId.
How can I do this?
I can do it by converting address Flux to a HashMap and then get values based on address id. But if I do that, am I leaving the reactive programming style? Is there any other way I can do this mapping?
public class Student {
private int id;
private int addressId;
private String name;
private String address;
}
public class Address {
private int id;
private String address;
}
public class MapperClass {
public void map(Flux<Student> students, Flux<Address> addresses ){
//For each student, I want to take address from addresses map and update the Student class's address field.
// I can do something like below:
addresses.collectMap(a -> a.getId(), a-> a.getAddress()).block();
}
}
Your solution uses blocking method, so it's not reactive. You could construct desired Flux in a reactive way like that:
Flux<Student> updatedStudents = addresses
.collectMap(Address::getId, Address::getAddress)
.flatMapMany(addressesMap ->
students.doOnNext(student -> student.address = addressesMap.get(student.addressId))
);
How does it work: first, via collectMap
you get Mono<Map<Integer, Address>>
, when it's collected, students
flux would be executed making use of that map.
It is required that 1) Flux<Address>
is not consumed anywhere else 2) Flux<Address>
is finite. Otherwise desired behaviour is not possible.