[SalesForce] Future Method and Static Variables

I have a class that implements Process.Plugin. It calls the invoke method, which calls a future method, which calls a webservice. The returned value from the webservice should be the output parameters. My issue is the static variables do not seem to be retaining their value outside of the future method.

I assume this has something to do with Async vs Sync methods but if anyone could explain as to why the result variable isn't holding it's value after the webservice is completed, I would appreciate it!

global class FlowToWebservice_Class implements Process.Plugin {
   public static Map<String,Object> result;
   ...

global static Process.PluginResult invoke(Process.PluginRequest request){
    varProcessName = (String)request.inputParameters.get('varProcessName');
    varCreditReviewId = (String)request.inputParameters.get('varCreditReviewId');
    callWebService(varProcessName , varCreditReviewId);
    return new Process.PluginResult(result);//the value of `result` is null so this will never return output parameters
}

@future(callout=true)
global static void callWebService(String processName, String crId) {
    k = JSON.serialize(new Map<String, object> {'Parameters' => new Map<String, object> {'CreditReviewId' => crId},'RulesSet' => processName}); 
    req = new HttpRequest();
    req.setEndpoint(endpointURL);
    req.setMethod('POST');
    req.setBody(k);
    req.setHeader('Content-Type', 'application/json');
    req.setTimeout(120000);
    string d = getAuth();
    req.setheader('Authorization', d);
    try {
        Http h = new Http();
        res = h.send(req);
        JSONParser parser = JSON.createParser(res.getBody());
        while (parser.nextToken() != null) {
            ....
        }
    }
    catch (System.CalloutException z) {
        system.debug('z: ' + z);
    }
    result = new Map<String,Object>();
    result.put('varResult',finalDecision);
    result.put('varROSID', relatedOppSearchId);
    result.put('varDeclineReason', declineReason);
}

Best Answer

Static variables in Apex only retain their value through the course of a single transaction. Future methods by nature execute in a separate transaction, which means that your static variables are reset. You cannot use static variables to return a value from a future method to the synchronous code that called it.

Related Topic