Publish a Platform Event From Within a Platform Event Apex Trigger – Question

platform-eventtransactiontrigger

My scenario is the following:

  1. an Opportunity is updated
  2. for some updates, the Opportunity before update trigger needs to update one or more OpportunityLineItems. The before update trigger cannot do the updates directly (exceptions are thrown); the trigger therefore publishes a Platform Event UpdateLinitems__e with publish behaviour Publish After Commit.
  3. the UpdateLineItems__e after insert trigger updates the line items based on the information in the event.
  4. next, the UpdateLineItems__e after insert trigger publishes a Platform Event UIRefresh__e which will be handled by a VF page. The VF page rerenders the entire page or parts thereof.

The Question is: what is the correct publish behavior setting for the UIRefresh__e event?

I guess the answer depends on whether or not we are in a transaction while the UpdateLineItems__e trigger is executing and / or on what happens when an event is published with behavior Publish After Commit when there is no current transaction.

  • when the UpdateLinitems__e trigger is executing within a transaction, the event must certainly be published after commit, otherwise the event might be consumed before the commit.
  • when the UpdateLinitems__e trigger is not executing within a transaction I need to know what happens when I publish UIRefresh__e with Publish After Commit outside of a transaction context. For instance, when not in a transaction, is Publish After Commit the same as Publish Immediately ? That is, when in doubt, I can always use Publish After Commit?

Best Answer

Having got into a mess using Publish Immediately, generally I recommend using Publish After Commit.

The "mess" for me was that the event publishing transaction's changed data is invisible to other transactions until it commits. So code subscribing to a Publish Immediately event from that transaction that needs to present or otherwise process that transactions changed data can't see the changes because it is running before the commit.

Related Topic