having the following code that produces a continuous flux of random strings :
@RestController
public class WebFluxController {
private final Random random = new Random();
@CrossOrigin
@GetMapping(value = "/documents")
public Flux getDocuments() {
return Flux.interval(Duration.ofSeconds(1))
.map(x -> "document-"
random.nextDouble());
}
}
...how can I replace the random with a query to the database that will return a field of the last record, something like :
@RestController
public class WebFluxController {
@Autowired
private ReactiveDocumentRepository reactiveDocumentRepository;
@CrossOrigin
@GetMapping(value = "/documents")
public Flux getDocuments() {
return Flux.interval(Duration.ofSeconds(1))
.map(x -> "document-"
reactiveDocumentRepository.findLastDocument().map(d->d.getDescription);
}
}
}
...where reactiveDocumentRepository.findLastDocument() returns a mono containing last document inserted in the db? In other words, I want that query to be ran continuously over the database and publish last inserted record all the time
CodePudding user response:
In reactive you need to build a flow using operators that will be evaluated when downstream (in your case webflux) subscribes to the flow. Result is not immediately available and you can't just concatenate it with a string. reactiveDocumentRepository.findLastDocument()
is reactive and you need to use flatMap
instead of map
.
public Flux getDocuments() {
return Flux.interval(Duration.ofSeconds(1))
.flatMap(x ->
reactiveDocumentRepository.findLastDocument()
.map(d -> "document-" d.getDescription)
);
}