ApexSensei

Drills Asynchronous Apex

Publish a Platform Event

Asynchronous Apex · Beginner · 10 min · Runs in the browser, no org needed · Apex Path

Construct a `Shipment_Update__e` event from the class fields and publish it with `EventBus.publish`. This draft grades the shape only. The event type is not deployed.

Lesson

Why this matters

A shipment notice should reach subscribers without inserting a regular record you then query. A Platform Event is a named message. You construct it and publish it. Subscribers run later, in their own transaction. Publishing does not wait on them.

The smallest working example

EventBus.publish(new Shipment_Update__e(
    Sku__c = sku,
    Quantity__c = quantity
));

Event type names end in __e. Custom fields end in __c.

Name the parts

  • **ShipmentNotice** holds sku and quantity.
  • **publish** constructs new Shipment_Update__e with those two fields.
  • **EventBus.publish** is the call that sends it.
  • Do not query or insert a regular sObject in place of the event.

A common wrong version

insert new Shipment_Update__e(Sku__c = sku, Quantity__c = quantity);

Events are not saved with insert. They are published.

The fix

Construct the event from the fields and pass it to EventBus.publish.

Now you try

Fill publish. Keep the class and its two fields.

Learn more

The challenge

Finish publish so it constructs Shipment_Update__e from the fields and publishes it.

Examples:

  • sku SKU-9, quantity 3 → an event with those two fields
  • EventBus.publish is the call that sends it

Requirements:

  1. EventBus.publish should be present: publish calls EventBus.publish.
  2. new Shipment_Update__e should be present: the method constructs Shipment_Update__e.
  3. Sku__c should be present: the event sets Sku__c from the class field.
  4. Quantity__c should be present: the event sets Quantity__c from the class field.

Starter code

public class ShipmentNotice {
    public String sku;
    public Integer quantity;

    public void publish() {
    }
}

Related drills

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Attach a Queueable Finalizer