AfterUndelete.Dispatcher
Make one bulk call per chunk with the records that qualify, such as enqueueing a Queueable or publishing events.
Signature
apex
public interface Dispatcher extends AfterUndelete.Handler {
Boolean dispatchOnAfterUndeleteWhen(TriggerTypes.UndeleteRecord record);
void dispatchOnAfterUndelete(TriggerTypes.UndeleteRecords records);
}dispatchOnAfterUndeleteWhen(record): called once per record in the chunk. Returntrueto include the record in the dispatch.dispatchOnAfterUndelete(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 AfterUndelete.Dispatcher {
public Boolean dispatchOnAfterUndeleteWhen(TriggerTypes.UndeleteRecord record) {
return record.isNotNull(Contact.Email);
}
public void dispatchOnAfterUndelete(TriggerTypes.UndeleteRecords 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) {
}
}
}Rules
- Pass Ids, not rows. Hand
records.getIds()to async work and query the records there. - Call out from a Queueable. Give the job
Database.AllowsCalloutsand make the callout inexecute. - No unit of work. DML in
dispatchOnAfterUndeleteruns at once and is not merged. DML in the predicate throws. Change records from a Writer. - Writer wins. A class that also implements
AfterUndelete.Writerruns only as a Writer.
WARNING
The Dispatcher runs before the commit. A Publish Immediately event sent here reaches subscribers even if the restore fails later.
Test
apex
@IsTest
static void dispatchOnAfterUndeleteWithEmail() {
// Setup
Contact doe = new Contact(LastName = 'Doe', Email = 'jane.doe@example.com');
TriggerOrchestrator.mock().afterUndeleteFor(ContactDispatcher.class).with(doe);
// Test
TriggerOrchestrator.runTestFor(new ContactDispatcher());
// Verify
Assert.areEqual(1, Limits.getQueueableJobs(), 'One job should be enqueued for the chunk.');
}