Skip to content

Instantly share code, notes, and snippets.

@scolladon
Last active February 13, 2025 06:31
Show Gist options
  • Save scolladon/1233ef10048479e967120fdef28044bc to your computer and use it in GitHub Desktop.
Save scolladon/1233ef10048479e967120fdef28044bc to your computer and use it in GitHub Desktop.
Dynamic Platform Event Publish with callback
public class PlatformEventPublishExplorationTest implements EventBus.EventPublishFailureCallback {
/* Execute Anonymous section
PlatformEventPublishExplorationTest.publishGenericType();
PlatformEventPublishExplorationTest.publishStaticType();
PlatformEventPublishExplorationTest.publishDynamicType();
*/
public void onFailure(EventBus.FailureResult result) {
System.Debug('Event publishing failed');
}
// Does not work, as stated in the doc
public static void publishGenericType() {
final SObject event = buildEvent('generic');
final List<SObject> events = new List<SObject>{
event
};
EventBus.publish(events, new PlatformEventPublishExplorationTest());
}
// Works, as stated in the doc
public static void publishStaticType() {
final MyPE__e event = (MyPE__e) buildEvent('static');
final List<SObject> events = new List<MyPE__e>{
event
};
EventBus.publish(events,new PlatformEventPublishExplorationTest());
}
// Works !!
public static void publishDynamicType() {
final SObject event = buildEvent('dynamic');
final List<SObject> events = (List<SObject>)Type.forName( 'List<' + MyPE__e.SObjectType.getDescribe().getName() + '>' ).newInstance();
events.add(event);
EventBus.publish(events, new PlatformEventPublishExplorationTest());
}
private static SObject buildEvent(final string value) {
final SObjectType eventType = MyPE__e.SObjectType;
final SObject event = eventType.newSObject(null, true);
event.put('Field__c', value);
return event;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment