Publish and subscribe

Publish and subscribe is typically used for getting notifications of a system wide event (along with Central Repository). The Publish and Subscribe API allows system-wide global variables to be set and retrieved, and allows subscribers to be notified that variables have changed. Publish and Subscribe is used for transient data.

For more information about security issues with publish and subscribe, see Publish and Subscribe in the Security section.

The Publish and Subscribe API is accessed through the RProperty class, which is defined in e32property.h. The publishing thread specifies which properties will be accessible from other threads:

const TUid KMyPropertyUid = {0x11234567};
enum TMyPropertyKeys = { EMyPropertyName1, EMyPropertyName2 };
//here the first property is defined to be integral type
RProperty myProperty;
myProperty.Define( KMyPropertyUid, EMyPropertyName1, RProperty::EInt);

Properties are published using RProperty::Set() functions, either by using an earlier attached property handle or by specifying the property category and key with the new value:

const TInt KNumber = 42; 
myProperty.Set( KMyPropertyUid, EMyPropertyName1, KNumber );

Properties can be deleted using RProperty::Delete() functions:

myProperty.Delete( KMyPropertyUid, EMyPropertyName1 );

Properties can be retrieved with RProperty::Get() functions:

TInt value; 
myProperty.Get( KMyPropertyUid, EMyPropertyName1, value );

Subscribing to a property is typically implemented with active objects. Subscription is typically done during active object construction (ConstructL() function) and the notifications are handled in active object's RunL() function.

void CExampleSubscriber::ConstructL()
        {
        User::LeaveIfError( iProperty.Attach(
                                          KmyPropertyUid,
                                          EMyPropertyName1 )
                                        );
         CActiveScheduler::Add(this);
          }
void CExampleSubsriber::Subscribe()
         {
         iProperty.Subscribe(iStatus);
         SetActive();
          }
void CExampleSubsriber::RunL()
          {
          // resubscribe before processing new value
          // to prevent missing updates
         Subscribe();
          TInt value;
          //never trust that the property has really changed
          //first make a check for deletion
          if( iProperty.Get(value) == KErrNotFound) )
               {
               //property deleted, take appropriate actions
               }
          else
               {
               //value changed
               }
          }

When implementing the active object, call the Cancel() function of the RProperty member in the DoCancel() function. In the destructor, the active object is cancelled in the normal way (by calling Cancel() function), and then the RProperty member is closed.