4

I have a data source service, which takes an observer as a parameter.

void subscribe(Consumer onEventConsumer);

I want to use flux as a response stream for RSocket. How can I do this? As I see it now, it should be something like

Flux<T> controllerMethod(RequestMessage mgs) {
   var flux = Flux.empty();
   dataSource.subscribe(event -> flux.push(event));
   return flux;
}

But I have big doubts that it's a proper solution, and I'm new in the reactive approach, I don't know what methods I should use here?

Mr.Ustiik
  • 305
  • 1
  • 5
  • 17

2 Answers2

3

As Simon already pointed out, this is what you use Flux.create for.

Take a look at the Getting Started Guide on projectreactor.io.

In short, you register a custom listener inside the lambda of the create method:

Flux<String> bridge = Flux.create(sink -> {
    myEventProcessor.register( 
      new MyEventListener<String>() { 

        public void onDataChunk(List<String> chunk) {
          for(String s : chunk) {
            sink.next(s); 
          }
        }

        public void processComplete() {
            sink.complete(); 
        }
    });
});

What you want to do is to pass the incoming elements on to a FluxSink, which will then publish those elements on the Flux.

rupweb
  • 3,052
  • 1
  • 30
  • 57
kerner1000
  • 3,382
  • 1
  • 37
  • 57
0

this is a typical use case of Flux.create. you register an obsereer from inside the create lambda, which will pass the data it receives down to the provided FluxSink

Simon Baslé
  • 27,105
  • 5
  • 69
  • 70
  • Is your suggestion valid in the case where we want to add an element to the flux following an Http call ? i.e a client sends a POST request to an endpoint with the message he wants to publish. thank you – Saad Moumen Dec 01 '20 at 13:30
  • that sounds like a completely different use case. in OP's case, a single `Flux` needed to reflect a single listener established by calling (as I understand non-reactive) `subscriber(Consumer)`. in your case it sounds like multiple calls to that endpoint should all publish to the same `Flux`. Look into the `Sinks` API in 3.4.0 for that. – Simon Baslé Dec 02 '20 at 15:31
  • That's exactly what I did! It's SO well-made and seems to cover the Safe production from multiple threads. Thank you Simon. – Saad Moumen Dec 03 '20 at 16:40