Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to force to execute Future callback function in Android UIThread.
import scala.concurrent._
import ExecutionContext.Implicits.global
import android.util.Log
import android.widget.TextView
class UIDemoActivity extends Activity {
override def onCreate(bundle: Bundle) {
super.onCreate(bundle)
val tv = new TextView(this)
setContentView(tv)
//pass ExecutionaContext.Implicits.global Implicitly.
val x: Future[Long] = future {
Log.d("FutureTest", "Future task is executed at:"+Thread.currentThread().getName)
val args = List.range(1, 1000000L)
args.sum
}
Log.d("FutureTest", "Future instance is created at:"+Thread.currentThread().getName)
//pass UIExecutionContext eplicitly.
val mine = new UIExecutionContext(this)
x.onSuccess {
case count =>
Log.d("FutureTest", "Future task callback is executed at:"+Thread.currentThread().getName)
tv.setText(tv.getText + " onSuccess!:"+count.toString )
}(mine)
/**
* LogCat.
* Future instance is created at:main
* Future task is executed at:ForkJoinPool-1-worker-5
* Future task callback is executed at:main
*/
}
}
import concurrent.ExecutionContext
import android.app.Activity
class UIExecutionContext(activity:Activity) extends ExecutionContext{
def execute(runnable: Runnable): Unit = activity.runOnUiThread(runnable)
def reportFailure(t: Throwable): Unit = t match{
case NonFatail(e) => e.printStackTrace()
case _ => throw t
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment