AfterUpdate.Finalizer
Runs once after an after update Writer or Dispatcher has processed its records, with the records that qualified. Use it for one bulk query or registration per chunk instead of work per record.
Interface
apex
public class AfterUpdate {
public interface Finalizer {
void finalizeAfterUpdate(TriggerHandler.UpdateRecords records);
}
}finalizeAfterUpdate(records): called once per chunk, after this handler’s records, only if at least one record qualified; after the dispatch for a Dispatcher. It receives only the qualified records.
Example
apex
public with sharing class ContactWriter implements AfterUpdate.Writer, AfterUpdate.Finalizer {
private TriggerHandler.UnitOfWork unitOfWork;
public Boolean writeOnAfterUpdateWhen(TriggerHandler.UpdateRecord record) {
return record.isChanged(Contact.AccountId);
}
public void writeOnAfterUpdate(TriggerHandler.UpdateRecord record, TriggerHandler.UnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
}
public void finalizeAfterUpdate(TriggerHandler.UpdateRecords records) {
for (Id accountId : records.getIdsOf(Contact.AccountId)) {
this.unitOfWork.toUpdate(new Account(Id = accountId, Description = 'Contacts changed'));
}
}
}Good to Know
- Once per chunk. It is not a hook for the whole statement: an update of 1,000 records runs it 5 times.
- Queries see this update. A query here returns the trigger records with their saved new values.
- Keep the unit of work in a field. The Finalizer gets no unit of work. Store the one from the action, as the Skeleton does. Those registrations commit with the rest.
- Runs before the commit. A Writer's Finalizer runs before any of its registrations are saved.
- Direct DML runs at once. DML here is not merged with the unit of work and costs its own statement.
