How to Track Message Subscribers Using Event Handlers

by on April 23, 2019

Today we are going to demonstrate how to create a simple event handler to track subscriber statistics on your various messaging channels. This gives you the ability to easily track the number of subscribers for each of your channels to help you manage channel load and gauge user interest in specific topics. Used in combination with API usage tracking, you will have a great sense of what your users are doing within your app.

Tracking Messaging Subscribers

To start, we will create a new application and call it Messaging_Statistics.

Create new Backendless App

Next, create a table with the necessary columns (described below). Go to the Data section and create a table with the name Subscribers:

Add New Table in Backendless Console

Next, we will add two columns to the table – ChannelName (with the type string) and CountSubscribers (with the type integer, or INT). To do this, go to the Schema tab of our table:

Create new Column in Backendless Schema Manager

Create new Column in Backendless Schema Manager

Now that the table is ready, we need to create listeners for events, such as adding a new subscriber to any channel. We will do this on the Event Handlers tab of the Business Logic (Cloud Code) section:

Create Event Handler in Backendless Console

Once we’ve created the handler, download the Java code:

Download event handler Java code

For more detail about how to run this code, we recommend reading the documentation: Developing Backendless Server Code with Java.

Add the following code:

public void afterSubscribe( RunnerContext context, String channel, SubscriptionOptions options, ExecutionResult<String> result ) throws Exception
  Backendless.Data.of( "Subscribers" ).find();
  Optional<Map> channelEntity = Backendless.Persistence.of( "Subscribers" ).find().stream()
          .filter( map -> map.get( "ChannelName" ).equals( channel ) ).findFirst();
  if( channelEntity.isPresent() )
    int count = (int) channelEntity.get().get( "CountSubscribers" ) + 1;
    channelEntity.get().put( "ChannelName", channel );
    channelEntity.get().put( "CountSubscribers", count );
    Backendless.Persistence.of( "Subscribers" ).save( channelEntity.get() );
    Backendless.Data.of( "Subscribers" ).save(
            new HashMap<String, Object>()
              put( "ChannelName", channel );
              put( "CountSubscribers", 1 );
            }} );

Let’s see if everything works the way we expect it to. To test, let’s subscribe to the channel by following the instructions. Next, let’s make some requests and see what happens.

Test new event handler

Test new event handler

Test new event handler

Everything works! Thanks for reading and enjoy using the Backendless platform!

Leave a Reply