How to publish Platform Event using Apex code?

How to publish Platform Event using Apex code?

Sample Code:
 
List < Test__e > listEvents = new List <Test__e >();

listEvents.add( new Test__e( Serial_No__c = ‘12345’ ) );
listEvents.add( new Test__e( Serial_No__c = ‘67890’ ) );

List < Database.SaveResult > results = EventBus.publish( listEvents );
for ( Database.SaveResult sr : results ) {
    if ( sr.isSuccess() ) {
        System.debug( ‘Event successfully published event.’ );
    } else {
        for(Database.Error err : sr.getErrors()) {
            System.debug( ‘Error code: ‘ + err.getStatusCode() );
            System.debug( ‘Error message: ‘ +   err.getMessage() );
        }
    }
}

Leave a Reply