Using Platform Events with Queueable Apex

Scenario: Learn how to invoke Queueable Apex within platform events.

Step 1: Integrate a button on the Salesforce UI, which could either be a vlocity action or a vlocity Omniscript guided flow, to invoke the “Apex Handler”.

Step 2: The “Apex Handler” will then trigger the Platform Event. Here’s a sample code for this step:

Demo_Platform_Event__e peObj = new Demo_Platform_Event__e(EndPoint_Url__c = endPointUrl);
Database.SaveResult sr = EventBus.publish(peObj);
if (sr.isSuccess()) {
System.debug('Successfully published Demo_Platform_Event__e Event.');
} else {
for(Database.Error err : sr.getErrors()) {
System.debug('Error on Publishing Demo_Platform_Event__e Event: ' + err.getStatusCode() + ' - ' + err.getMessage());
}
}

Step 3: Upon invocation, the “Platform Event” will initiate the “Trigger”. You can set this up by navigating to Setup > Platform Events > New Platform Events. Then, add the necessary Trigger and Custom Fields.

Step 4: Within the “Trigger”, call the Queueable Apex. The trigger can be bulkified to a batch size of 50, which is the limit supported by Queueable. Here’s a sample code:

trigger demoTriggerHandler on Demo_Platform_Event__e(after insert) {
List<Demo_Platform_Event_e__e> peListItems = new List<Demo_Platform_Event_e__e>();
Integer counter = 0;
for(Demo_Platform_Event_e__e peObj : peListItems) {
counter++;
System.debug('Counter = '+ counter);
if (counter >= 50) {
break;
} else {
peListItems.add(peObj);
}
EventBus.TriggerContext.currentContext().setResumeCheckpoint(peObj.ReplayId);
}
calloutHelper objCallout = new calloutHelper(peList);
ID jobID = System.enqueueJob(objCallout);
System.debug('jobID = '+ jobID);
}

Step 5: The “Queueable Apex” will initiate an “HTTP callout” to an external system. Here’s a sample HTTP callout:

Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(endPointUrl);
req.setMethod('PUT');
req.setBody(inputData);
req.setHeader('content-type', 'application/json');
req.setHeader('Accept', 'application/json');
HTTPResponse res = http.send(req);
outputMap.put(KEY_RESULTS, res.getBody());
Integer statusCode = res.getStatusCode();
System.debug('code =' + statusCode);
if(statusCode == 200) {
// logic on success
} else {
// handle exception
}

For more details on the Queueable Apex code base, refer to the Salesforce documentation.

 

Was this article helpful?
YesNo

Similar Posts