---
url: https://trigger.beyondthecloud.dev/after-insert/dispatcher.md
description: >-
  Make one bulk call per chunk after insert - enqueue a Queueable, publish
  events or send email for the records that qualified.
---

# AfterInsert.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 AfterInsert.Handler {
    Boolean dispatchOnAfterInsertWhen(TriggerTypes.InsertRecord record);
    void dispatchOnAfterInsert(TriggerTypes.InsertRecords records);
}
```

* `dispatchOnAfterInsertWhen(record)`: called once per record in the chunk. Return `true` to 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**

::: code-group

```apex [Skeleton]
public with sharing class ContactDispatcher implements AfterInsert.Dispatcher {
    public Boolean dispatchOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isNotNull(Contact.Email);
    }

    public void dispatchOnAfterInsert(TriggerTypes.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) {
        }
    }
}
```

:::

## Rules {#rules}

* **Pass Ids to async work.** Let the job query what it needs.
* **No unit of work.** A Dispatcher never gets one, and OwnUnitOfWork is ignored. DML in `dispatchOnAfterInsert` runs at once and is not merged. DML in the predicate throws. Use a [Writer](/after-insert/writer) for record writes.
* **Publish with `EventBus.publish(events)`.** It runs at once, before the shared unit of work commits.
* **Writer wins.** A class that also implements `AfterInsert.Writer` runs only as a Writer.

::: warning
No synchronous callouts. A callout from a trigger throws, so enqueue a Queueable that implements `Database.AllowsCallouts`.
:::

## Test {#test}

```apex
@IsTest
static void dispatchOnAfterInsertWithEmail() {
    // Setup
    Contact doe = new Contact(LastName = 'Doe', Email = 'jane.doe@example.com');

    TriggerOrchestrator.mock().afterInsertFor(ContactDispatcher.class).with(doe);

    // Test
    TriggerOrchestrator.runTestFor(new ContactDispatcher());

    // Verify
    Assert.areEqual(1, Limits.getQueueableJobs(), 'One job should be enqueued for the chunk.');
}
```
