Last active
March 30, 2016 15:45
-
-
Save yareally/5941536 to your computer and use it in GitHub Desktop.
Basic usage example of Scala's async/await (https://github.com/scala/async) on Android
This file contains hidden or 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
/* | |
Copyright (c) 2013 Wes Lanning, http://codingcreation.com | |
Permission is hereby granted, free of charge, to any person obtaining | |
a copy of this software and associated documentation files (the | |
"Software"), to deal in the Software without restriction, including | |
without limitation the rights to use, copy, modify, merge, publish, | |
distribute, sublicense, and/or sell copies of the Software, and to | |
permit persons to whom the Software is furnished to do so, subject to | |
the following conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | |
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | |
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
http://www.opensource.org/licenses/mit-license.php | |
*/ | |
package com.example.android_scala | |
import android.app.Activity | |
import android.os.Bundle | |
import android.widget.{Toast, TextView} | |
import scala.async.Async.{async, await} | |
import scala.concurrent.{Await, Future, ExecutionContext, future} | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration._ | |
import scala.io.Source | |
import android.util.Log | |
/** | |
* Test converting a Java Interface to a Scala Lambda | |
* via implicits. | |
* | |
* @author Wes Lanning | |
* @version 2013-10-10 | |
*/ | |
class AsyncActivity extends Activity | |
{ | |
/** | |
* Auto converts a Java Runnable interface to a Scala Lambda | |
* Just an example of removing the bloat from Java when using Scala | |
* | |
* @param funct - the function to implement for run() | |
* @return the implemented Runnable object | |
*/ | |
implicit def runnableAsLambda(funct: () => Unit) = new Runnable { | |
def run() = funct | |
} | |
override def onCreate(savedInstanceState: Bundle) | |
{ | |
super.onCreate(savedInstanceState) | |
val TEST_URL = "https://raw.github.com/yareally/android-scala-intellij-no-sbt-plugin/testing/test-download-1.txt" | |
val TEST_URL_2 = "https://raw.github.com/yareally/android-scala-intellij-no-sbt-plugin/testing/test-download-2.txt" | |
/** | |
* Fetches the contents of a file as a string and wraps it in a Future. | |
* This function will run asynchronously. | |
* | |
* @param url - the url to fetch | |
* @return a string wrapped in a Future result | |
*/ | |
def getRemoteFile(url: String): Future[String] = future { | |
val readme = Source.fromURL(url) | |
readme.mkString | |
} | |
/** | |
* This function denotes that we have asynchronous code we want to run via the "async" keyword | |
* the "async" keyword tells the compiler to look for any "await" areas and make them non-blocking | |
* in our example, we wish to fetch the contents of 2 files via http in a non-blocking manner | |
* | |
* @return a string wrapped in a Future result | |
*/ | |
def httpResult: Future[String] = async { | |
// stop here and wait for the result from above if it's not done yet | |
// fetch the files in parallel via separate threads simultaneously for efficiency | |
val resultPage = await(getRemoteFile(TEST_URL)) + await(getRemoteFile(TEST_URL_2)) | |
// return the file as a string (variable creation was for clarity purposes) | |
resultPage | |
} | |
// Below line serves no purposes other than to demonstrate how to use the implicit function runnableAsLambda | |
//runOnUiThread(() => Toast.makeText(this, "Toast Message here", Toast.LENGTH_SHORT).show()) | |
setContentView(R.layout.main) | |
Toast.makeText(getApplicationContext, s"fetching remote test file from: $TEST_URL and $TEST_URL_2", Toast.LENGTH_SHORT).show() | |
val textView = findViewById(R.id.async_result).asInstanceOf[TextView] | |
textView.setText("When the http result is done, this will be replaced with the content of the page.") | |
// wait for the asynchronously fetched http results | |
// then unwrap the result from the future to get the string | |
val pageContent: String = Await.result(httpResult, 10.seconds) | |
Toast.makeText(this, "Test file download complete!", Toast.LENGTH_SHORT).show() | |
textView.setText(pageContent) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment