0

I have a simple batch with global variable as :

global with sharing class sampleBatchApex implements Database.Batchable<sObject>{

    global List<Case> myList;


    global Database.QueryLocator start(Database.BatchableContext BC){
 
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope){
      //some stuff;
    }

    global void finish(Database.BatchableContext BC){
      myList = SELECT ID ... FROM ...
    }
}

And an other where I try to get myList

public class BatchApexProgressIndicatorController {
   public static sampleBatchApex myBatchObject = new sampleBatchApex();

the batch is executed in an other method, and I'm monitoring the job. Once it's finished, I'm calling the following method to get myList

  @AuraEnabled
  public static List<Case> getCases(){
    return myBatchObject.myList;
  }

}

It keeps me getting empty list.

However if I System.debug the list in the finish method of the batch, i can see that the list is not empty.

Could you please hint me on how can I get this list from the other class ?

Thank you

AshBringer
  • 2,614
  • 2
  • 20
  • 42

1 Answers1

0

You can't do that. Batch Apex and @AuraEnabled Lightning controller code execute in completely separate transaction contexts; they do not share any variables.

When your batch class is enqueued for execution it is serialized and later deserialized and executed by the platform. Your calling code does not retain a reference to the actual, executing batch instance. Further, your class isn't declared with the Database.Stateful marker interface, so it won't retain member variable values between btches in any case.

You'll need to use a different strategy to monitor your batch job, depending on just what your batch job does. This could be polling sObjects with SOQL, posting Platform Events from the batch, etc.

David Reed
  • 2,522
  • 2
  • 16
  • 16