Skip to content

Instantly share code, notes, and snippets.

@beatmadsen
Created January 23, 2020 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beatmadsen/c81c069e3df28de075c82fcc8e08044e to your computer and use it in GitHub Desktop.
Save beatmadsen/c81c069e3df28de075c82fcc8e08044e to your computer and use it in GitHub Desktop.
An example of an asynchronous service using futures to be run on an event loop
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class FileApp(val fileCounter: FileCounter) extends Service {
private def countWordsV1(number: Int): Future[Int] = fileCounter.countWordsInFile(s"${number}a")
.flatMap(c1 => fileCounter.countWordsInFile(s"${number}b").map(c2 => c1 + c2))
private def countWordsV2(number: Int): Future[Int] = {
for {
c1 <- fileCounter.countWordsInFile(s"${number}a")
c2 <- fileCounter.countWordsInFile(s"${number}b")
} yield c1 + c2
}
def apply(line: String): Future[String] = Future.unit.map { _ =>
// NB: the following line might throw an exception
// so we're doing the conversion inside `map`
// to wrap any exception in a failed future
line.toInt
}.flatMap(i => countWordsV2(i)).map(_.toString)
}
trait FileCounter {
def countWordsInFile(id: String): Future[Int]
}
/**
* The service that you "plug in" to the event loop.
* The event loop calls the `apply()` function when a new line is ready
* and
*/
trait Service {
def apply(line: String): Future[String]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment