Scala android and actors
Scala expressiveness strikes back !
A sample showing iteration between scala actors and android.Activity
Extending activity with a trait to receive events from another actors, services, or any other source ( listeners , as a observer … )
class MainActivity extends Activity
with ActivityUtil
with Reactive {
override def onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
button(R.id.Button01).onClicked {
app.actor ! Ping(this)
}
}
onReact {
case Pong(count) => onUi {
textView(R.id.Label1).setText("Pong -> " + count)
}
}
}
Isn’t she pretty ?
- ActivityUtil
- Allow us to access activity components directly
button(R.id.Button01)
- Allow us to access activity components directly
- Reactive
- Converts the activity into a scala actor
- Calling onReact with the desired partialFunctions, allow us to manage the external events
onReact { case Pong(count) => onUi { textView(R.id.Label1).setText("Pong -> " + count) } }One problem, onReact resides inside another thread ( the actor one ), so to access components of the view, we must use onUi function
- ViewConversions
- With a bunch of implicit conversions, we can implement Listeners directly with functions
button(R.id.Button01).onClicked { app.actor ! Ping(this) }
- With a bunch of implicit conversions, we can implement Listeners directly with functions
- The application class contains the other actor who returns Pong
class App extends Application { val actor = new SampleActor override def onCreate(): Unit = { actor.start } } case class Pong(count: Int) case class Ping(a: Actor) class SampleActor extends Actor with L { private var count = 0 def act() { loop { receive { case Ping(a) => { count = count + 1 a ! Pong(count) } } } } }
I just remembered why I love scala so much
PD: I used giter8 to get a scala-android template
g8 gseitz/android-sbt-project
- giter8 https://github.com/n8han/giter8
- template home https://github.com/gseitz/android-sbt-project.g8
- scala-home http://www.scala-lang.org/
- sample-code https://github.com/jgoday/sample_android_scala_actor


