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 ?

 

  1. ActivityUtil
    • Allow us to access activity components directly

      
      button(R.id.Button01)
  2. 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

  3. ViewConversions
    • With a bunch of implicit conversions, we can implement Listeners directly with functions

      
      button(R.id.Button01).onClicked {
          app.actor ! Ping(this)
      } 
  4. 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 

 

Advertisement
    • brant.yan
    • August 3rd, 2011

    HI Jgoday:
    can you mail this project code to me . I start learn scala recently. My email is
    daaoke@msn.com

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.