Clone wiki

Android Async / Home

Android Async

This is a small library to help with running long running tasks without blocking the thread they're started on. Callbacks are made on completion. The role it fills is similar to AsyncTask, except more flexible, and nicer to use.

Standard Java concurrency tools like Futures, Executors, Callables, etc are used.

Code Sample

Here's a quick hello world example.

// Run a one off asynchronous operation which will generate a message
// on a background thread and send it back to our UI thread
Async.doAsync(
	// Key to identify the operation. Not needed in this example
	null,
	// The object which is run asynchronously to produce a result. 
	// In this case our object produces a common message :)
	new Callable<String>() {
		@Override
		public String call() throws Exception {
			return "Hello World!";
		}
	},
	// An outcome receives the result of the async operation once it's
	// finished. Either the succeeded or failed method is called 
	// depending on whether the operation threw an exception when it was
	// run.
	new Outcome<Void, String>() {
		@Override
		protected void succeeded(Void key, String result) {
			mHelloWorldText.setText(result);
		}
		
		@Override
		protected void failed(Void key, Throwable error) {
			// This will never happen in this simple example
			throw new RuntimeException(error);
		}
	},
	// A notifier is responsible for telling the outcome when the 
	// operation has finished. Here we use a notifier which always sends
	// messages on the UI thread which makes it safe for us to update
	// Android UI Views
	Notifiers.newThreadSpecificNotifier(new Handler())
);

Updated