Skip to content

PhilippHeuer/events4j

Repository files navigation

Events4J

Latest OpenSSF Scorecard

Bugs Code Smells Duplicated Lines (%) SonarCloud Coverage

Click the module name in the table below for specific import instructions. (gradle, maven, ...)

Module Javadoc Description
Lib Javadoc contains all interfaces
Lib Javadoc contains the EventManager implementation
Lib improvements for usage in kotlin projects
Lib Javadoc a simple synchronous event handler
Lib Javadoc a event dispatcher using project reactor
Lib Javadoc forward events to spring ApplicationEventPublisher

Description

Events4J provides the following features:

  • publish events
  • register consumers / listeners for events
  • comes with a few prebuilt handlers that you can use out of the box
  • provide your custom implementation to process events however you want

Usage

Initialization

EventManager eventManager = new EventManager(); // new instance
eventManager.autoDiscovery(); // register modules automatically

Event Producer

TestEvent testEvent = new TestEvent();
eventManager.publish(testEvent);

Event Consumer

Subscriber-based

IEventManager eventManager = new EventManager();
ReactorEventHandler reactorEventHandler = new ReactorEventHandler(eventManager);
eventManager.registerEventHandler(reactorEventHandler);

The Consumer

reactorEventHandler.onEvent(TestEvent.class).subscribe(event -> {
    log.info("TestEvent received");
});

Simple

If you want to use annotation-based events, you need to enable this feature. Annotation-based event consumers are disabled by default.

IEventManager eventManager = new EventManager();
SimpleEventHandler simpleEventHandler = new SimpleEventHandler();
eventManager.registerEventHandler(simpleEventHandler);

The Consumer

public class TestEventListener {

    @EventSubscriber
    public void onTestEvent(TestEvent testEvent) {
        System.out.println("TestEvent received");
    }

}

Register the Consumer

eventManager.registerListener(new TestEventListener());

Spring Events

Configure the following in your application.properties to enable spring application events:

events4j.handler.spring.enabled: true

The Consumer

@EventListener
public void handleContextStart(TestEvent testEvent) {
    System.out.println("TestEvent received");
}

Kotlin

The kotlin module allows the usage of flows to consume events.

eventManager.flowOn<TestEvent>()
    .collect { testEvent ->
        println("TestEvent received")
    }

License

Released under the MIT License.