Skip to main content

Event Model

At the code level, different systems often still call each other directly or indirectly. To reduce code coupling, you can use Hasor's event mechanism for deeper decoupling.

Hasor events have three execution models:

  • Synchronous with a dedicated thread.
  • Synchronous with a shared thread.
  • Asynchronous.
ModelMain flowListener execution
Synchronous, dedicated threadFire event → wait → continue after listeners finishRuns on an event thread; completion releases the waiting caller
Synchronous, shared threadFire event → run listeners → continueRuns on the calling thread
AsynchronousFire event → continue immediatelyRuns independently on an event thread

Whether the event model is synchronous or asynchronous, events in Hasor share the following characteristics:

  • Event listeners execute in registration order.
  • Event listeners use the same interface.
  • Event registration uses the same approach.

Registering Event Listeners

Implement a listener
import net.hasor.core.EventListener;
public class MyListener implements EventListener<Object> {
public void onEvent(String event, Object eventData) throws InterruptedException {
Thread.sleep(500);
System.out.println("Receive Message:" + JSON.toJSONString(eventData));
}
}
Obtain the EventContext interface
ApiBinder apiBinder = ...
EventContext ec = apiBinder.getEventContext();

or

AppContext appContext = ...;
EventContext eventContext = appContext.getInstance(EventContext.class);

or

EventContext eventContext = appContext.getEventContext();

or

public class MyBean {
@Inject
private EventContext eventContext;
}

Then register the event in the container through EventContext.

Register an event listener
EventContext eventContext = ...
eventContext.addListener("EventName",new MyListener());

Firing Events

Example
eventContext.fireSyncEvent("EventName",...);