Skip to content

Broadcasting messages

Igor Zinken edited this page Dec 24, 2021 · 1 revision

If you wish to broadcast messages related to engine state or the state of any of its actors, you can use the Notifier and Observer classes, which use a basic publish/subscribe pattern. Messages are sent over a message bus that will notify any of registered observers that given message has fired.

Broadcasting messages

By including the notifier.h header you can broadcast a message from anywhere by simply calling its static broadcast methods:

broadcast( int notificationType );
broadcast( int notificationType, int notificationValue );

Where notificationType is an identifier for a unique notification event (see <definitions/notifications.h> for the basic enum). Your messages can also broadcast an optional payload value which (at the time of writing) is an integer of your choice. Use the overloaded method for this purpose.

Observing messages

In order to capture the message and take action, you will need to use Observers to listen for messages. The way you are using MWEngine inside your project determines how to do so:

Using Notifier/Observer solely from C++

If you wish to subscribe to messages directly from your native code, you will need to register and unregister your Observer instance directly.

registerObserver( int notificationType, Observer* observer);
unregisterObserver( int notificationType, Observer* observer);

where notificationType is the identifier of the notification and observer is a pointer to an Observer instance. Whenever the notification of given identifier fires, given Observer will be notified with the notifications payload.

Using Notifier/Observer in Java/Kotlin

In Java, all notifications are handled by the MWEngine instance. Upon construction of the MWEngine class you will have provided an instance of class implementing the MWEngine.IObserver interface. The overloaded methods there can be extended to handle your custom broadcasts. E.g.:

public void handleNotification( final int notificationId, final int notificationValue ) {
    switch ( _notificationEnums[ notificationId ]) {
        case NOTIFICATION_TYPE_1:
            // do something with given notificationValue
            break;
    }
}

Also see the example MWEngineActivity.

Clone this wiki locally