How does the Iterable interface work in Batch Apex for custom data collections?
Answer
Basics: When the work list is not a simple SOQL result, such as records parsed from an external API, a merge of two objects, or a filtered subset that SOQL cannot express, you return an Iterable from start() instead of a QueryLocator.
How it works:
- Implement
Database.Batchable<T>;start()returnsIterable<T>(aListalready qualifies, or write a class implementingIterableandIterator). - The framework calls
iterator(), thenhasNext()andnext()to build each scope. - Each scope goes to its own
execute()transaction. - Add
Database.AllowsCalloutsifexecute()makes callouts (start()itself can make callouts only with it as well).
Advanced / deep dive: start() runs as one transaction, so the 50,000 SOQL row limit, heap (6 MB sync context rules apply in start; batch start runs as async with 12 MB) and CPU apply to everything you assemble. A custom Iterator can lazily generate items to keep memory low, but the iterator object is serialized between chunks, so keep it small and serializable. For huge but structured data, prefer a QueryLocator; or paginate: have start() return only IDs or page tokens and fetch details in execute(). Apex Cursors (newer feature, verify availability in your release) are another way to page through large SOQL results in async code.
Code / config example:
public .Batchable<SObject>, Database.AllowsCallouts {
Iterable<SObject> {
List<SObject> work = <SObject>();
(Account a : [SELECT Id, Name FROM Account WHERE Name LIKE LIMIT ]) {
work.add(a);
}
work;
}
{
}
{}
}