Search
The Basics

Asynchronous Messaging

This is the one concept you'll need to get used to--and you'll get used to it fast--as messages in Errai are completely asynchronous. There's no request-response pattern here.

Every message has a sender and at least one receiver. A receiver is as it sounds--it receives the message and does something with it. Implementing a receiver (also referred to as a service) is as simple as implementing our standard MessageCallback interface, which is used pervasively across, both client and server code. Let's look at an example:


import org.jboss.errai.bus.client.CommandMessage;
import org.jboss.errai.bus.client.MessageCallback;
import org.jboss.errai.bus.server.annotations.Service;

@Service("HelloWorld")
public class HelloWorld implements MessageCallback {
    public void callback(CommandMessage message) {
        System.out.println("Hello, World!");
    }
}

This above example declares a service with the subject name HelloWorld. We implement the callback() method of the MessageCallback interface. Our service will simply print "Hello, World!" when it receives a message. Pretty simple.

In fact, you just learned about 40% of everything you need to know about federating services on the ErraiBus.  We told you that you'd get used to this fast. Let's learn the next 40%.

A service that is not used is not a very useful thing.  So let's create an extremely simple GWT application that sends a message to our HelloWorld service.

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import org.jboss.errai.bus.client.CommandMessage;
import org.jboss.errai.bus.client.ErraiBus;
import org.jboss.errai.bus.client.MessageBus;

public class HelloWorld implements EntryPoint {
    /**
     * Get an instance of the MessageBus
     */

    private MessageBus bus = ErraiBus.get();

    public void onModuleLoad() {
        Button clickMe = new Button("Click Me!");

        /**
         * Register a click handler for the button.
         */

        clickMe.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                /**
                 * Send a message to the 'HelloWorld' service.
                 */

                CommandMessage.create()
                        .toSubject("HelloWorld")
                        .sendNowWith(bus);
           }
        });

        /**
         * Just add the button to the RootPanel in the DOM.
         */

        RootPanel.get().add(clickMe);
    }
}

This is a simple example GWT application, that renders a button on the webpage, and sends a message to the "HelloWorld" subject that we declared up above. 
 

         

Further Reading