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** holdsskuandquantity. - **
publish** constructsnew Shipment_Update__ewith 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, quantity3→ an event with those two fields EventBus.publishis the call that sends it
Requirements:
- EventBus.publish should be present:
publishcallsEventBus.publish. - new Shipment_Update__e should be present: the method constructs
Shipment_Update__e. - Sku__c should be present: the event sets
Sku__cfrom the class field. - Quantity__c should be present: the event sets
Quantity__cfrom the class field.
Starter code
public class ShipmentNotice {
public String sku;
public Integer quantity;
public void publish() {
}
}
Related drills
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.