0

While looking at the source code of the WiretapConnector from Spring framework I stumbled upon an object of type MonoProcessor. I tried Googling explanations of uses for it but to no avail.

Javadoc doesn't say much to a Reactive/Reactor layperson:

A MonoProcessor is a Mono extension that implements stateful semantics. Multi-subscribe is allowed. Once a MonoProcessor has been resolved, newer subscribers will benefit from the cached result.

This last sentence hints that the result of calculation is cached and it seems this to be the use of MonoProcessor in this code.

Could someone clarify what would be the intended use-case of MonoProcessor and why was it introduced in the first place?

Matej
  • 7,728
  • 4
  • 23
  • 30

1 Answers1

1

The use case is you want a processor that creates a "hot" Mono, not a Flux. Also provides processor functions such as cancel, dispose, onNext etc. Since Mono is a single value, it in turn can only consume a single onNext and as such the result is cached for any future subscriptions. Effectively turning it from a "hot" to "cold".

Example of hot Mono

   //Set up flux processor, sink for thread safety
    DirectProcessor<Integer> directProcessor = DirectProcessor.create();
    FluxSink<Integer> sink = directProcessor.serialize().sink();

    //Allows dynamic creation of Mono value, after initialisation
    MonoProcessor<Integer> processor =
            directProcessor.filter(s -> s > 5)
            .next()
            .toProcessor();

     //Set up subscriptions, no values have been submitted to either yet
     processor.map(i -> "monoProc: " + i).subscribe(System.out::println);
     directProcessor.map(i -> "DirectProc: " + i).subscribe(System.out::println);

    //Uncomment and above Mono subscription will never occur
    //processor.cancel();

    //Values from some other service or whatever
    for (int i = 0; i < 10; i++) {
        sink.next(i);
    }

    //Do something later with cached result
    processor.map(i -> "monoProc cached: " + i).subscribe(System.out::println);
123
  • 10,778
  • 2
  • 22
  • 45
  • When would you use `toProcessor` over `cache`. From what I can tell, both of these provide a cached mono result. One thing I can see is the `MonoProcessor` subscription can be cancelled - is this the only thing? – Tobiq Nov 24 '21 at 13:37