Skip to content

Instantly share code, notes, and snippets.

@taisukeoe
Last active April 16, 2017 05:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taisukeoe/7812514 to your computer and use it in GitHub Desktop.
Save taisukeoe/7812514 to your computer and use it in GitHub Desktop.
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