Notifications - Code

Allow game makers to message players, regardless if game is running [LIVE-Notifications-02]

Overview

The Notifications feature can be accessed via the NotificationsService from the Beamable API. Notifications primarily function using a Publish-subscribe pattern, where objects that should react to incoming messages (the "subscribers") listen for messages being sent out by another object (the "publishers"). Following this pattern, the API is quite simple.

Usages

Example Callback Function

When a subscribed object receives a message, the message carries some data with it that can provide extra content about the event that occurred. For the purposes of this document, this function will be used:

void CallbackAction(object callbackObject)
{
    //Some code that uses the callback object
}

Subscribe/Unsubscribe

Subscriptions are DBID based, so an event published by the server (e.g., a microservice) must specify your DBID in order for your client to receive the event.

var beamable = BeamContext.Default;

//Start listening to events published with the specified message name
beamable.Api.NotificationService.Subscribe("messageName", CallbackAction );

//Stop listening for events with the specified message name
beamable.Api.NotificationService.Unsubscribe("messageName", CallbackAction );

Publish (from Client)

var exampleObject = new object();

//Publish an event with data that will be passed to subscribers
beamable.Api.NotificationService.Publish("messageName", exampleObject);

The code above is a few snippets from the client-side C# API. However, another supported use-case is calling NotificationService functions from a microservice. This has the distinct advantage of allowing a microservice to "call back" to a client application when something of interest happens. Rather than publishing a generic event by name, the microservice can actually supply one or more specific player DBIDs to notify.

Publish (from Microservice)

public async Task SendNotificationFromMicroservice(List<long> dbids, string context, object payload)
{
    var json = JsonUtility.ToJson(payload);
    await Services.Notifications.NotifyPlayer(dbids, context, json);
}

Did this page help you?