Search code examples
javaspringrx-javaproject-reactorreactive-streams

Java Flux vs. Observable/BehaviorSubject


My question is whether or not Flux has the ability to behave like an Observable or BehaviorSubject. I think I get the gist of what a Flux does and how, but every tutorial I see creates a Flux of static content, i.e. some pre-existing array of numbers which are finite in nature.

However, I want my Flux to be a stream of unknown values over time... like an Observable or BehaviorSubject. With those, you can create a method like setNextValue(String value), and pump those values to all subscribers of the Observable/BehaviorSubject etc.

Is this possible with a Flux? Or does the Flux have to be composed of an Observable type stream of values first?

Update

I answered my own question with an implementation down below. The accepted answer will lead down same path probably, but slightly complicated.


Solution

  • This can be achieved like this:

    private EmitterProcessor<String> processor;
    private FluxSink<String> statusSink;
    private Flux<String> status;
    
    public constructor() {
        this.processor = EmitterProcessor.create();
        this.statusSink = this.processor.sink(FluxSink.OverflowStrategy.BUFFER);
        this.status = this.processor.publish().autoConnect();
    }
    
    public Flux<String> getStatus() {
        return this.status;
    }
    
    public void setStatus(String status) {
        this.statusSink.next(status);
    }