Reputation: 6612
I have a web method that returns a flux object when it will be time (it's linked to a pub/sub). Would it at least be possible, only for the first call, to return a default?
public Flux<String> receiveStream() {
return myReactiveService.getData() //here can I return a value at start? //.map(...);
Upvotes: 0
Views: 520
Reputation: 28301
It is not that easy to do it "only for the first call". Each request is supposed to get its own sequence of Strings, unless you take specific steps to change that. And that is at two levels:
- WebFlux
: each request leads to a separate invocation of the controller method, so the Flux
is newly instantiated
- Reactor
: most Flux
are "cold", ie they don't generate data until they're subscribed to, and each subscription regenerates a separate dataset.
So even if you returned a cached Flux
, it would probably still serve each request separately.
There is a way to share()
a long-lived Flux
so that later newcomers only see data that becomes available after they've subscribed to the shared Flux
, which could help with the "only the first request" aspect of your requirement.
Assuming getData()
by itself is cold (ie simply calling it doesn't trigger any meaningful processing):
AtomicReference<Flux<String>> sharedStream = new AtomicReference<>();
public Flux<String> receiveStream() {
Flux<String> result = sharedStream.get();
if (result == null) {
Flux<String> coldVersionWithInit = myReactiveService
.getData()
.startWith(FIRST_VALUE)
.map(...);
Flux<String> hotVersion = coldVersionWithInit.share();
if (sharedStream.compareAndSet(null, hotVersion))
result = hotVersion;
else
result = sharedStream.get();
}
return result;
}
Upvotes: 2