Guava Custom EventBus Example

Guava Custom EventBus Example

Last tutorial you saw how to use Google Guava EventBus after registering subscriber. In this example we will create CustomEventBus class which will extend EventBus class and will use its register method inside constructor to register subscriber. As this CustomEventBus class will be center point of registering all component and can be found out easily:

  • CustomEvent.java:
package com.javahonk.eventbus;

import com.google.common.eventbus.EventBus;

public class CustomEvent extends EventBus{
	
	EventSubscriber1 eventSubscriber1;
	EventSubscriber2 eventSubscriber2;
	
	public CustomEvent(EventSubscriber1 eventSubscriber1, EventSubscriber2 eventSubscriber2 ) {	
		
		this.eventSubscriber1 = eventSubscriber1;
		this.eventSubscriber2 = eventSubscriber2;
		register(eventSubscriber1);	
		register(eventSubscriber2);		
	}

}
  • EventHolder.java:
package com.javahonk.eventbus;

public class EventHolder {
	
	private String greetingMessage;

	public EventHolder(String greetingMessage) {
		this.greetingMessage = greetingMessage;
	}

	public String getGreetingMessage() {
		return greetingMessage;
	}
	

}
  • EventSubscriber1.java:
package com.javahonk.eventbus;

import com.google.common.eventbus.Subscribe;

public class EventSubscriber1 {
	
	private String greetings1;
	
	@Subscribe
	public void getMessage(EventHolder eventSenderClass) {
		greetings1 = eventSenderClass.getGreetingMessage();
		
	}

	public String getGreetings1() {
		return greetings1;
	}
	
}
  • EventSubscriber2.java:
package com.javahonk.eventbus;

import com.google.common.eventbus.Subscribe;

public class EventSubscriber2 {
	
	private String greetings2;
	
	@Subscribe
	public void getMessage(EventHolder eventSenderClass) {
		greetings2 = eventSenderClass.getGreetingMessage();
		
	}

	public String getGreetings2() {
		return greetings2;
	}
	
}
  • EventPublisher.java:
package com.javahonk.eventbus;


public class EventPublisher {

	public static void main(String[] args) {
		
		EventSubscriber1 eventSubscriber1 = new EventSubscriber1();
		EventSubscriber2 eventSubscriber2 = new EventSubscriber2();
		CustomEvent customEvent = new CustomEvent(eventSubscriber1,eventSubscriber2);
		
		customEvent.post(new EventHolder("Hello from event bus: Java Honk."));
	    
	    System.out.println("Subscriber1 got message: "+eventSubscriber1.getGreetings1());
	    System.out.println("Subscriber2 got message: "+eventSubscriber2.getGreetings2());	

	}

}
  • Output: Run EventPublisher.java you will see below output:

Guava Custom EventBus Example

  • For more information please visit Google Guava library here

Leave a Reply

Your email address will not be published. Required fields are marked *