AfterInsert.Dispatcher
Selects new records with a predicate, then acts once per chunk with the ones that qualified. Use it to enqueue a Queueable, publish events or send email.
Interface
apex
public class AfterInsert {
public interface Dispatcher extends Handler {
Boolean dispatchOnAfterInsertWhen(TriggerHandler.InsertRecord record);
void dispatchOnAfterInsert(TriggerHandler.InsertRecords records);
}
}dispatchOnAfterInsertWhen(record): called once per record in the chunk; it only selects records. Returntrueto include the record in the dispatch.dispatchOnAfterInsert(records): called once, after every record was checked, with the qualified records; not called when none qualified.
Example
apex
public with sharing class ContactDispatcher implements AfterInsert.Dispatcher {
public Boolean dispatchOnAfterInsertWhen(TriggerHandler.InsertRecord record) {
return record.isNotNull(Contact.Email);
}
public void dispatchOnAfterInsert(TriggerHandler.InsertRecords records) {
System.enqueueJob(new ContactSyncJob(records.getIds()));
}
public class ContactSyncJob implements Queueable {
private Set<Id> recordIds;
public ContactSyncJob(Set<Id> recordIds) {
this.recordIds = recordIds;
}
public void execute(QueueableContext context) {
}
}
}Good to Know
- Pass Ids to async work. Enqueue one job with
records.getIds()and let the job query what it needs. - No unit of work. A Dispatcher never gets one, and OwnUnitOfWork is ignored. DML here runs at once and is not merged. Use a Writer for record writes.
- Runs before the shared commit. The Writers' registrations are not saved yet, even from Writers listed earlier. A Publish Immediately event goes out even if that commit fails.
- No synchronous callouts. A callout from a trigger throws. Enqueue a Queueable that implements
Database.AllowsCallouts. - Writer wins. A class that also implements
AfterInsert.Writerruns only as a Writer.
Test
apex
@IsTest
static void dispatchOnAfterInsertWhenEmailIsSet() {
// Setup
Contact newContact = new Contact(Email = 'jane.doe@example.com');
// Test
Boolean isQualified = new ContactDispatcher().dispatchOnAfterInsertWhen(new TriggerHandler.TriggerRecord(newContact, null));
// Verify
Assert.isTrue(isQualified, 'A contact with an email should be dispatched.');
}