[SalesForce] Flow Invocable Apex – FLOW_ELEMENT_ERROR The number of results does not match

I'm trying to use invocable apex within a record triggered flow to create a static flag to ensure that code only runs once for each transaction.

When I update more than one record I'm getting error:

FLOW_ELEMENT_ERROR The number of results does not match the number of interviews that were executed in a single bulk execution request.

I've tried adding the results with the invocable method to a static List, to ensure that the number of returned elements is equal to the number of invocations, but I'm still getting the same error.

public class FlowInvocable {
    private static boolean run = true;
    private static List<boolean> boolList = new List<boolean>();
    @InvocableMethod
    public static List<boolean> runOnce() {
        if(run){
            run=false;
            boolList.add(true);
            return boolList;
        }else{
            boolList.add(false);
            return boolList;
        }
    }
    
}

The flow:

Record Triggered Flow Trigger – a record is created or updated, run flow after record is updated

then the only connected element is the invocable action above.

Best Answer

When an InvocableMethod runs, it runs against all interviews in a batch at once. As such, the number of outputs, if any, must match the number of inputs.

In order to fix this error, you need to pass in some value so you can return a list of values all at once.

Something more appropriate would look like:

static Set<Id> recordsProcessed = new Set<Id>();
@InvocableMethod static Boolean[] runOnce(Id[] recordIds) {
  Boolean[] results = new Boolean[0];
  for(Id recordId: recordIds) {
    results.add(recordsProcessed.add(recordId));
  }
  return results;
}

What is happening here is that we call the Set.add method to add the record Id to the Set. If the value already exists in the Set, this method returns false, meaning that the record has already been processed once. If the value does not exist in the Set, the method returns true, meaning that the record has not yet been processed.