HomeGuidesAPI Reference
Submit Documentation FeedbackJoin Developer CommunityLog In
Hey! These docs are for version 2.1.0-full-stack, which is no longer officially supported. Click here for the latest version, 1.0!

Register notification listeners

Notification listeners trigger a callback function of your choice when certain actions are triggered in the SDK. The most common use case is to build custom analytics integrations that forward impressions and conversion events on to other systems. For example, you can send a stream of all experiment activations to an internal data warehouse and join it with other data you have about your users.

Currently, we support two types of listeners:

  • ACTIVATE triggers a callback with the experiment, user ID, attributes, variation, and the impression event.
  • TRACK triggers a callback with the event key, user ID, attributes, and event tags.

Activate and track listeners can be added by accessing the notification listener instance variable off of your Optimizely instance. Define your closure, function, lambda, or class (depending on the language) and add it to the notification center. The listeners are called on every subsequent event. Listeners are added per event type, so there is a listener for activate and a listener for track. The example code shows how to add a listener, remove a listener, remove all listeners of a specific type (for example, all activate listeners), and remove all listeners.

import com.optimizely.ab.notification.ActivateNotificationListener;
import com.optimizely.ab.notification.NotificationCenter;
import com.optimizely.ab.notification.TrackNotificationListener;

OptimizelyClient optimizelyClient = optimizelyManager.getOptimizely();
// Add an Activate listener
int notificationId = optimizelyClient.getNotificationCenter().addNotificationListener(NotificationCenter.NotificationType.Activate, new ActivateNotificationListener() {
    @Override
    public void onActivate(@Nonnull Experiment experiment, @Nonnull String userId, @Nonnull Map<String, String> attributes, @Nonnull Variation variation, @Nonnull LogEvent event) {
        logger.debug("activate called for experiment {} on {}", experiment.getKey(), userId);
    }
});

// Add a Track listener
int trackNotificationId = optimizelyClient.getNotificationCenter().addNotificationListener(NotificationCenter.NotificationType.Track, new TrackNotificationListener() {
    @Override
    public void onTrack(@Nonnull String eventKey, @Nonnull String userId, @Nonnull Map<String, String> attributes, @Nonnull Map<String, ?> eventTags, @Nonnull LogEvent event) {
        logger.debug("track was called for event {}", eventKey);
    }
});

// Remove a notification listener
optimizelyClient.getNotificationCenter().removeNotificationListener(notificationId);
// Remove all notification listeners
optimizelyClient.getNotificationCenter().clearAllNotificationListeners();

// Remove all notification listeners of a certain type.
optimizelyClient.getNotificationCenter().clearNotificationListeners(NotificationCenter.NotificationType.Track);
using OptimizelySDK;
using OptimizelySDK.Entity;
using OptimizelySDK.Event;
using OptimizelySDK.Notifications;
using NotificationType = OptimizelySDK.Notifications.NotificationCenter.NotificationType;

var optimizelyClient = new Optimizely(datafile);


NotificationCenter.ActivateCallback OnActivate = (Experiment experiment, string userId, UserAttributes userAttributes, Variation variation, LogEvent logEvent) => {
  Console.WriteLine(experiment.Key);
  Console.WriteLine(userId);
};

NotificationCenter.TrackCallback OnTrack = (string eventKey, string userId, UserAttributes userAttributes, EventTags eventTags, LogEvent logEvent) => {
  Console.WriteLine(eventKey);
  Console.WriteLine(userId);
};

// Add an Activate notification listener
int activateId = optimizelyClient.NotificationCenter.AddNotification(NotificationType.Activate, OnActivate);
// Add a Track notification listener
int trackId = optimizelyClient.NotificationCenter.AddNotification(NotificationType.Track, OnTrack);

// Remove notification listener
optimizelyClient.NotificationCenter.RemoveNotification(activateId);

// Clear all notification listeners of a certain type
optimizelyClient.NotificationCenter.ClearNotifications(NotificationType.Activate);

// Clear all notifications
optimizelyClient.NotificationCenter.ClearAllNotifications();
import com.optimizely.ab.notification.ActivateNotificationListener;
import com.optimizely.ab.notification.NotificationCenter;
import com.optimizely.ab.notification.TrackNotificationListener;

// Add aN Activate listener
int notificationId = optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Activate, new ActivateNotificationListener() {
    @Override
    public void onActivate(@Nonnull Experiment experiment, @Nonnull String userId, @Nonnull Map<String, String> attributes, @Nonnull Variation variation, @Nonnull LogEvent event) {
        logger.debug("experiment {} was activated for user {}", experiment.getKey(), userId);
    }
});

// Add a Track listener
int trackNotificationId = optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Track, new TrackNotificationListener() {
    @Override
    public void onTrack(@Nonnull String eventKey, @Nonnull String userId, @Nonnull Map<String, String> attributes, @Nonnull Map<String, ?> eventTags, @Nonnull LogEvent event) {
        logger.debug("track was called for user {} on event {}", userId, eventKey);
    }
});
// Remove a notification listener
optimizely.notificationCenter.removeNotificationListener(notificationId);
// Remove all notification listeners
optimizely.notificationCenter.clearAllNotificationListeners();
// Remove all notification listeners of a certain type
optimizely.notificationCenter.clearNotificationListeners(NotificationCenter.NotificationType.Track);
const optimizelyEnums = require('@optimizely/optimizely-sdk/lib/utils/enums');

function onActivate(activateObject) {
  console.log(
    'activate called for experiment %s',
    activateObject.experiment['key'],
  );
}

function onTrack(trackObject) {
  console.log('track called for event %s', trackObject.eventKey);
}

// Add an ACTIVATE notification listener
const activateId = optly.notificationCenter.addNotificationListener(
  optimizelyEnums.NOTIFICATION_TYPES.ACTIVATE,
  onActivate,
);

// Add a TRACK notification listener
const trackId = optly.notificationCenter.addNotificationListener(
  optimizelyEnums.NOTIFICATION_TYPES.TRACK,
  onTrack,
);

// Remove a specific listener
optly.notificationCenter.removeNotificationListener(activateId);

// Remove listeners for a specific notification type
optly.notificationCenter.clearNotificationListeners(
  optimizelyEnums.NOTIFICATION_TYPES.TRACK,
);

// Remove all listeners
optly.notificationCenter.clearAllNotificationListeners();
const NOTIFICATION_TYPES = require("@optimizely/optimizely-sdk/lib/utils/enums")
  .NOTIFICATION_TYPES;

function onActivate(activateObject) {
  console.log(
    `activate called for experiment ${activateObject.experiment.key}`
  );
}

function onTrack(trackObject) {
  console.log(`track called for event ${trackObject.eventKey}`);
}

// Add an ACTIVATE notification listener
let activateId = optimizelyClient.notificationCenter.addNotificationListener(
  NOTIFICATION_TYPES.ACTIVATE,
  onActivate
);

// Add a TRACK notification listener
let trackId = optimizelyClient.notificationCenter.addNotificationListener(
  NOTIFICATION_TYPES.TRACK,
  onTrack
);

// Test it out
optimizelyClient.activate("my_experiment", userId);
optimizelyClient.track("my_conversion", userId);

// Remove a specific listener
optimizelyClient.notificationCenter.removeNotificationListener(activateId);

// Remove listeners for a specific notification type
optimizelyClient.notificationCenter.clearNotificationListeners(
  NOTIFICATION_TYPES.TRACK
);

// Remove all listeners
optimizelyClient.notificationCenter.clearAllNotificationListeners();
// Add an Activate notification listener
NSInteger activateNotificationId = [optimizely.notificationCenter addActivateNotificationListener:^(OPTLYExperiment *experiment, NSString *userId, NSDictionary<NSString *,NSString *> *attributes, OPTLYVariation *variation, NSDictionary<NSString *,NSString *> *event) {
    [logger logMessage:@"activate called" withLevel:OptimizelyLogLevelDebug];
}];

// Add a Track notification listener
NSInteger trackNotificationId = [optimizely.notificationCenter addTrackNotificationListener:^(NSString * _Nonnull eventKey, NSString * _Nonnull userId, NSDictionary<NSString *,NSString *> * _Nonnull attributes, NSDictionary * _Nonnull eventTags, NSDictionary<NSString *,NSObject *> * _Nonnull event) {
    [logger logMessage:@"track called" withLevel:OptimizelyLogLevelDebug];
}];


// Remove a sepcific listener
[optimizely.notificationCenter removeNotificationListener:activateNotificationId];
// Remove all of one type of listener
[optimizely.notificationCenter clearNotificationListeners:OPTLYNotificationTypeActivate];

// Remove all notification listeners
[optimizely.notificationCenter clearAllNotificationListeners];
public function onActivate($experiment, $userId, $attributes, $variation)
{
    print "activate experiment " . $experiment->getKey() . " for user " . $userId;
}             

public function onTrack($eventKey, $userId, $attributes, $eventTags, $event)
{     
    print "conversion event " . $eventKey . " for user " . $userId;
}

// Add an ACTIVATE listener
$activateId = $optimizelyClient->notificationCenter->addNotificationListener(
    NotificationType::ACTIVATE,
    onActivate
);

// Add a TRACK listener
$trackId = $optimizelyClient->notificationCenter->addNotificationListener(
    NotificationType::TRACK,
    onTrack
);

// Remove a specific notification listener        
$optimizelyClient->notificationCenter->removeNotificationListener($activateId);

// Remove all notification listeners of a certain type
$optimizelyClient->notificationCenter->clearNotifications(NotificationType::TRACK);

// Remove all notification listeners
$optimizelyClient->notificationCenter->clearAllNotifications();
from optimizely.notification_center import NotificationCenter
from optimizely.helpers import enums

def on_activate(experiment, user_id, attributes, variation, event):
  print('Activated experiment {0}'.format(experiment.key))

# Add an ACTIVATE Notification Listener
notification_id = opt_obj.notification_center.add_notification_listener(enums.NotificationTypes.ACTIVATE, on_activate)

def on_track(event_key, user_id, attributes, event_tags, event):
  print('Track event with event_key={0}'.format(event_key))

# Add a TRACK Notification Listener
note_id = self.optimizely.notification_center.add_notification_listener(
enums.NotificationTypes.TRACK, on_track)

# Remove Notification Listener
opt_obj.notification_center.remove_notification_listener(notification_id)
# Remove all Notification Listeners
opt_obj.notification_center.clear_all_notifications()
# Remove all Notification Listeners of a certain type
opt_obj.clear_notifications(enums.NotificationTypes.TRACK);
class track_callback
    def on_track(event_key, user_id, attributes, event_tags, event)
        @logger.log(Logger::DEBUG, "Event track for  '#{event_key}'.")
    end
end

class activate_callback
    def on_activate(experiment, user_id, attributes, variation, event)
        @logger.log(Logger::DEBUG, "Activated experiment '#{experiment['key']}'.")
    end
end

# Add an ACTIVATE notification listener
callback = activate_callback.new
callback_reference = callback.method(:on_activate)
activate_id = @optly.notification_center.add_notification_listener(Optimizely::NotificationCenter::NOTIFICATION_TYPES[:ACTIVATE], callback_reference)

# Add a TRACK notification listener
callback = track_callback.new
callback_reference = callback.method(:on_track)
track_id = @optly.notification_center.add_notification_listener(Optimizely::NotificationCenter::NOTIFICATION_TYPES[:TRACK], callback_reference)

# Remove a notification listener
@optly.notification_center.remove_notification_listener(activate_id)

# Remove notification listeners of a certain type
@optly.notification_center.clear_notification_listeners(Optimizely::NotificationCenter::NOTIFICATION_TYPES[:TRACK])

# Remove all notification listeners
@optly.notification_center.clear_all_notification_listeners()
// Add an activate notification listener
let activateNotificationId = optimizely?.notificationCenter?.addActivateNotificationListener({ (experiment, userId, attributes, variation, logEvent) in
    logger?.logMessage("activate event", with: OptimizelyLogLevel.debug)
})

// Add a track notification listener
let trackNotificationId = optimizely?.notificationCenter?.addTrackNotificationListener({ (eventKey, userId, attributes, eventTags, event) in
    logger?.logMessage("track event", with: OptimizelyLogLevel.debug)
})

// Remove a specific notification listener
optimizely?.notificationCenter?.removeNotificationListener(UInt(trackNotificationId!))

// Remove notification listeners of a certain type
optimizely?.notificationCenter?.clearNotificationListeners(OPTLYNotificationType.activate)

// Remove all notification listeners
optimizely?.notificationCenter?.clearAllNotificationListeners()

Did this page help you?