Provide Flux to signal events without a concrete value?

sschmeck :

How can I setup a stream/publisher with project Reactor that emits events over time but without any concrete values. I thought about Flux<Void> but the documentation mentions that Flux<Void> is an empty stream.

For example I consume a stream with filesystem changes Flux<Path>. I do not need the Path value but want to add another events. In order to do this I have to create dummy Path objects.

Flux<Path> events = getFilesystemChanges();
events.startWith(Path.of("dummy"))
      .map(e -> 42 /* subsequent operator ignores the emitted value */)
      ...

Is it possible to avoid the dummy values or is there maybe a convention to express that the values aren't read?

Michael Berry :

Reactive streams only work with objects (you can never stream null), and since Void can never be instantiated you can therefore never send any values - just a completion signal.

I'm not quite sure of the use case here, but there's two different approaches you can take that spring to mind:

  • If you never need the value, you can just map to an Object, i.e.

    Flux<Object> events = getFilesystemChanges().map(p -> new Object());
    

    You can then just use events.startWith(new Object()) and carry on. (You can pick a more appropriate type than Object if you want of course, or create your own.)

  • If you need the actual values emitted, but sometimes need to just interject your own "dummy" values, then you can have a stream of Optional<Path> instead:

    Flux<Optional<Path>> events = getFilesystemChanges().map(Optional::of);
    

    Then you can do events.startWith(Optional.empty()) to prepend a "dummy" path to the stream.

FWIW, the second approach I've often used for "heartbeat" type functions, where I want a stream of values to be emitted, but also want to ensure there's activity once every (timeperiod) to keep an underlying connection alive. The latter is where I'll often use empty optionals.

Guess you like

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