Is there a way to run code in Matlab App automatically _after_ the startup function runs?

27 Views Asked by At

I would like to have my app do some things in the background after the startup function runs. This should happen automatically without input from the user. The reason is that my app loads some large data files on startup, which makes it somewhat slow to start. I would like the user to be able to start interacting with the app while the large data files are being loaded in the background. The obvious (but impossible) way to do this would be to add some code in the app constructor, like this:

function app = myApp

    % Create UIFigure and components
    createComponents(app)

    % Register the app with App Designer
    registerApp(app, app.myAppUIFigure)

    % Execute the startup function
    runStartupFcn(app, @startupFcn)
    
    %%%%%%%%% App is open now, user can start interacting %%%%%%%%%%%%%
    
    %%%%%%%%%%%%%%%%% What I would like to do %%%%%%%%%%%%%%%%%%%%%%%%%%
    myData = parfeval(backgroundPool,@load,1,myBigDataSet,'theData');
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    if nargout == 0
        clear app
    end
end

Later when the data is needed, I could retrieve it with

myValues = fetchOutputs(myData);

However, I don't think it's possible to add my own code in the app constructor. Is there any other way to make my code run immediately after the app is constructed?

1

There are 1 best solutions below

0
Rich006 On

This doesn't directly answer the question, but it's a workaround. I put the parfeval call in the app startupFcn, so it starts loading data while the app is setting up, but the user doesn't have to wait for data to finish loading. Then when the user clicks "Run" in the app (to perform the app's actual function), the background-loaded data is retrieved by the callback function for that button-click. It takes less than a second to retrieve the data, whereas it was taking several seconds to wait for the data to load during app startup.

The user still has to wait some time after clicking "Run", but much less time than they had to wait for the data to load during app startup.