Skip to content
This repository was archived by the owner on Dec 20, 2019. It is now read-only.

Background Executor

Ángel Serrano edited this page Mar 27, 2014 · 2 revisions

All editor logic is run a single thread by default: the UI thread. This approach is more than enough for the majority of tasks performed by the editor, not affecting at all to the user experience. However, from time to time, the editor must perform more complicated tasks that can take some time to complete. Launching these actions in the UI thread would cause the UI to freeze until the task ends, affecting the user experience.

The Background Executor solves this problem given capabilities to launch background tasks in independent threads.

Launching a background task involves two objects: a BackgroundTask, which contains all the processing logic that will be executed in an independent thread, and a BackgroundTaskListener, that processes the result of the task in the UI thread.

Example

controller.getBackgroundExecutor().submit(
	// Background task with the heavy weight processing
	new BackgroundTask<String>() {
		@Override
		// Starts the execution of the process. Called in an independent thread.                 
		public String call() throws Exception {
			int loops = 10;
			for (int i = 0; i < loops; i++) {
				Thread.sleep(1000);
				setCompletionPercentage((float) i / (float) loops);
				}
				return "done";
			}
		// Background task listener, waiting for the process to end.
		// Three methods to listen for the completion percentage, for when the task is done
		// and for when the task fails, throwing an error.
		// All these methods are executed within the UI thread
		}, new BackgroundTaskListener<String>() {
			@Override
			public void completionPercentage(float percentage) {
				label.setText("Background task progress: " + percentage);
			}

			@Override
			public void done(BackgroundExecutor backgroundExecutor,
					String result) {
				label.setText("Done.");

			@Override
			public void error(Throwable e) {
			        Gdx.app.error("BackgroundTask", "Error", e);
			}
});

See Background Exectuor test or launch Background Task Demo for more examples.

Clone this wiki locally