Iterable Batch Apex
Let’s traverse through data!
The Database.Batchable interface contains three methods that must be implemented. Namely, the start, the execute and the finish.
The start method can return either a QueryLocator or something called Iterable. Just like the below code
public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
In this post, we are going to discuss the latter, which is Iterable.
Iterable<String> i = new List<String> { 'X', 'Y', 'Z' };
With this knowledge, we can quite easily implement a Batch Apex to iterate over a list like :
public with sharing class ExampleBatchApex implements Database.Batchable<String>
public Iterable<String> start(Database.BatchableContext BC){
return new List<String> { ‘Hello’, ‘ World‘, ‘ !!‘ };
}
public void execute(Database.BatchableContext info, List<String> strList){
//let’s do something with the string for fun
String myStr = strList.size() >0 ? strList[0] : '' ;
}
public void finish(Database.BatchableContext info) { }
}
// executing the batch apex
Id jobId = Database.executeBatch(new ExampleBatchApex());{
Most importantly, we can use this Iterable to traverse over generic List<object>
Consider an instance where you need to pass the entire list of objects which consists of different types of data such as string, Integer, Decimal, etc…
So we could take the advantage of Iterable shown below:
public with sharing class ExampleBatch implements Database.Batchable<object>
public List<object> objList = new List<Object>();
public ExampleBatch(List<Object> objList){
this.objList = objList;
}
public Iterable<object> start(Database.BatchableContext BC) {
return objList;
}
public void execute(Database.BatchableContext BC, List<object> scope){
List<Custom_object__c> customobjList = new List<Custom_Object__c>();
for(Object obj : scope){
Map<Object,Object> objMap = (Map<Object,Object>) obj ;
// Do something
}
// DML operation
}
public void finish(Database.BatchableContext BC) {
}
}
Thus, sometimes Iterable can be helpful and save time and effort.