How to close FileChooser immediately while using lambda?

I have a TextButton that opens up a FileChooser to load a file and I do a bunch of stuff when the file is chosen and opened. The problem is that the FileChooser stays open while I’m running my code which takes a while…and sometimes needs debugging…which means that dialog stays on the screen the whole time and in the way of the debugger. This is probably related to threading.

Is there any way to close that FileChooser immediately? Btw, I’m running Xcode.

Here’s my code:

loadButton.setButtonText("Load...");
	addAndMakeVisible(loadButton);
	loadButton.onClick = [this]{
		FileChooser fc ("Load...",
						File("~/someFolder"),
						String("*.xml"),
						true);
		
		if (fc.browseForFileToOpen())
		{
			File chosenFile = fc.getResult();
            // close fileChooser immediately
			loadXML(chosenFile); // <--- this takes a while and needs debugging
		}
	};

Try using Thread::launch (static function that takes a lambda) to run your xml loading code, so your program can continue to run and close the file dialog.

Or MessageManager::callAsync if you don’t want to start a separate thread. But note that this will execute loadXML on the message thread. The FileChooser will close, but it may block something else afterwards if it takes long.

Thanks. I tried a few things, but none will compile. I must be missing something…

File chosenFile;

MainComponent()
{
    loadButton.onClick = [this]{
	    FileChooser fc ("Load...",
					File("~/someFolder"),
					String("*.xml"),
					true);
	
	    if (fc.browseForFileToOpen())
	    {
	        chosenFile = fc.getResult();

            //No viable conversion from 'void' to 'std::function<void ()>'
            Thread::launch(loadXMLFile);   

            // No viable conversion from 'void (MainComponent::*)()' to 'std::function<void ()>'
            Thread::launch(&MainComponent::loadXMLFile);

        }
    };
}

void loadXMLFile()
{
    // load chosenFile
}

If you are trying to call a member function from a lambda, you need to capture “this” :

Thread::launch([this] () { loadXMLFile(); } );

You already capture “this” in the outer onClick lambda but each lambda will need its own captures.

Thank you!