Last active
February 13, 2025 06:31
-
-
Save scolladon/1233ef10048479e967120fdef28044bc to your computer and use it in GitHub Desktop.
Dynamic Platform Event Publish with callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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