software engineer. bicyclist & rock climber. craft beer addict.
Responsive Android Apps With Scala
When it comes to building responsive Android apps, there are two commandments:
Don’t block the UI thread, ever.
Only access and modify the UI from the UI thread itself.
The Android Dev Guide goes into some detail about this.
The usual solutions in Java are to:
Spawn a thread that does work and then invoke View.post
with a Runnable
that manipulates the UI.
Implement and run an AsyncTask
that does work in doInBackground, and then manipulates the UI in
onPostExecute.
As you can see, both these solutions — though they are the bread and butter of
Android development — are pretty verbose and unwieldy:
I prefer AsyncTask, which has better semantics, but implementing one
AsyncTask after another quickly becomes tedious. Same with writing line after
line of Runnable boilerplate.
The first step is to create an implicit conversion from a function to a Runnable,
which can then be passed to View.post or runOnUiThread. Once we’ve done
that, it’s simple to use spawn from scala.concurrent.ops
to do background work.
Here’s a fully functional example:
This is so much nicer than the Java alternative. Instead of up to ten lines of boilerplate
for each background task, we end up with just the spawn and runOnUiThread.
If you’re waiting for that final push to switch over to Scala for your Android development,
I highly recommend the sbt plugin for Android. Take
a look at its brilliant Getting Started guide,
which will have you up and running in just a few minutes.