Reactive Programming (Reactor)- Part 4- Hooks

Kondah Mouad
3 min readJul 4, 2021

Reactor hooks are a set of configurable lifecycle hooks that can be used for cross-cutting added behavior on Flux/Mono operators.

Dropping Hooks

Dropping hooks are invoked when the source of an operator does not comply with the Reactive Streams specification. These kind of errors are outside of the normal execution path.

Typically below, when onError is invoked and we are in a completion state (done)

In that case, the onError unexpected exception is dropped. The same is true for onNext signal.

Internal Error Hook

onOperatorError is invoked by operators when an unexpected Exception is thrown during the execution of their onNext, onError and onComplete signals.

Unlike the previous category, this is still within the normal execution path. A typical example is the map operator with a map function that throws an Exception.

A typical example is the map operator with a map function that throws an Exception, Operatots.onNextError will be first invoked

And if no strategy is defined, it will fallback to onOperatorError

onOperatorError hook lets you inspect the error (map the exception and check for fatal error viaExceptions.throwIfFatal(Throwable)).

we trigger finally our onError signal if we suppose that no strategy was defined.

Assembly Hooks

These hooks tie in the lifecycle of operators. They are invoked when a chain of operators is assembled (that is, instantiated).

The below code snippet shows how onEachOperator lets you dynamically change each operator as it is assembled in the chain, by returning a different Publisher.

onLastOperator is similar, except that it is invoked only on the last operator in the chain before the subscribe call (see Reactive Programming (Reactor)- Part 1 for more details about subscribe signal).

Conclusion

Reactor offers a variety of helpful hooks defined for handling different signals, we only covered some of them in this post, others hooks are left for investigation for interested people.

The next post will be dedicated to Reactor Schedulers.

References

https://www.packtpub.com/product/hands-on-reactive-programming-with-reactor/9781789135794

--

--