How to create multiple Flux from aysnc callbacks

Liang Chen :

From Reactor's reference guide, I learnt that Flux.create() can be used to convert aysnc callback to Flux.

However, sometimes callbacks have multiple methods to receive multiple types of data, assume I have piece of code as below:

asrService.recognize(new Callback() {
    @Override
    public void stateChange(State state) {
        // consume state
    }

    @Override
    public void onResultData(Result result) {
        // consume result
    }
});

How to convert it to two reactive streams: Flux<State> and Flux<Result>?

Ricard Kollcaku :

one way is to use Some processors Like DirectProcessor you can create 2 Different Processors and on event emit item to processor and subscribe the processor but if you still want to use Flux.create you can do it like this

    Flux<Object> objectFlux;

@Override
public void run(String... args) throws Exception {

    objectFlux = Flux.create(objectFluxSink ->
            asrService.recognize(new Callback() {
                @Override
                public void stateChange(State state) {
                    objectFluxSink.next(state);
                }

                @Override
                public void onResultData(Result result) {
                    objectFluxSink.next(state);
                }
            }));





}

public Flux<Result> getResult(){
 return    objectFlux.filter(o -> o instanceof Result)
            .map(o -> ((Result)o));
}

public Flux<State> geState(){
    return    objectFlux.filter(o -> o instanceof State)
            .map(o -> ((State)o));
}

i still think that using processor should be much more cleaner and you dont need to do that filter and casting but you need to have 2 Processors Like this :

        DirectProcessor <Result> resultDirectProcessor = DirectProcessor.create();
    DirectProcessor<State> stateDirectProcessor = DirectProcessor.create();
    asrService.recognize(new Callback() {
        @Override
        public void stateChange(State state) {
            stateDirectProcessor.onNext(state);
        }

        @Override
        public void onResultData(Result result) {
            resultDirectProcessor.onNext(result);
        }
    });

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=153253&siteId=1