Last active
April 16, 2017 05:01
-
-
Save taisukeoe/7812514 to your computer and use it in GitHub Desktop.
How to force to execute Future callback function in Android UIThread.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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