Skip to content

Instantly share code, notes, and snippets.

@samueltardieu
Created October 11, 2011 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samueltardieu/1277718 to your computer and use it in GitHub Desktop.
Save samueltardieu/1277718 to your computer and use it in GitHub Desktop.
Current (working but not polished) implementation of onUI and onBG
import scala.collection.mutable.{HashMap, Map}
import scala.concurrent.Channel
import scala.concurrent.ops.spawn
import android.content.Context
import android.os.{Handler, Message}
object AndroidBG {
private val androidBGs: Map[Context, AndroidBG] = new HashMap()
implicit def toAndroidBG(context: Context) = synchronized {
androidBGs.getOrElseUpdate(context, new AndroidBG(context))
}
def remove(context: Context) = synchronized {
androidBGs.remove(context)
}
}
class UIResult[A] extends Function0[A] {
private val channel: Channel[A] = new Channel
lazy val content: A = channel.read
override def apply = content
def write(data: A) = channel.write(data)
}
object UIResult {
implicit def toA[A](result: UIResult[A]) = result()
}
class AndroidBG(context: Context) {
AndroidBG.androidBGs.put(context, this)
val currentHandler = new Handler {
override def handleMessage(message: Message) = message.obj.asInstanceOf[() => Unit]()
}
def onBG(block: => Any): Unit = {
spawn {
try {
block
} finally {
AndroidBG.remove(context)
}
}
}
def onUI[A](block: => A): UIResult[A] = {
val answer: UIResult[A] = new UIResult
currentHandler.obtainMessage(0, () => answer.write(block)).sendToTarget
answer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment