2

I'm trying to stream changes to tables such as Accounts to a handler that will update our data warehouse. I tried pushtopics but ran into limitations in query size and longtext fields, so now I'm trying platform events. My cometd client is able to receive events that I publish to my platform event (as in this example) but I want to automate the process, and I can't seem to find any code where people have done this. Everything I see about triggers seems to be using triggers to subscribe to a platform event, instead of using them to publish events.

How do I automate the process of publishing platform events? Does my strategy here make sense?

3

Yes, you can do this in a trigger. It works almost the same as any other type of operation:

MyEventName__e[] events = new MyEventName__e[0];
for(...) {
  ...
  events.add(new MyEventName__e(SomeField__c=someValue, ...));
}
EventBus.publish(events);

However, please keep in mind that events that are published cannot be rolled back. If using a "partial update" mechanism or workflow/process builder updates, this may result in multiple published events, and if the transaction ultimately fails, subscribers will still see the published events. As such, you will want to consider this use case carefully.

If I were going to do this in a practical manner, I'd have a future/queueable method to call so that the events are published only after the transaction successfully completes.


trigger ... on ... (...) {
  ...
  EventPublisher.publishAsync(values);
}

public class EventPublisher {
  @future public static void publishAsync(...) {
    ...
    EventBus.publish(events);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.