Last active
December 19, 2015 10:38
-
-
Save yareally/5941489 to your computer and use it in GitHub Desktop.
scala async/await on android
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
package com.cc.json2csv | |
import android.app.Activity | |
import android.os.Bundle | |
import play.api.libs.json._ | |
import android.widget.TextView | |
import android.util.Log | |
import scala.async.Async.{async, await} | |
import scala.concurrent.{Await, Future, ExecutionContext, future} | |
import scala.concurrent.duration._ | |
import ExecutionContext.Implicits.global | |
/** | |
* @author Wes Lanning | |
* @version 2013-07-06 | |
*/ | |
class Test extends Activity | |
{ | |
override def onCreate(savedInstanceState: Bundle) | |
{ | |
super.onCreate(savedInstanceState) | |
def parseJson(lines: String): Future[JsValue] = future { | |
Json.parse(lines) | |
} | |
// define an async function | |
def jsonResult:Future[String] = async { | |
val source = scala.io.Source.fromFile("/sdcard/example.json") | |
val lines = source.mkString | |
source.close() | |
// stop here and wait for the result from above if it's not done yet | |
val json = await(parseJson(lines)) | |
Json.stringify(json) | |
} | |
// get our json result using the async functions above | |
val json: String = Await.result(jsonResult, 10.seconds) | |
setContentView(R.layout.main) | |
val textView = findViewById(R.id.test).asInstanceOf[TextView] | |
textView.setText(json) | |
Log.d("Test", "json result: " + jsonResult.value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment