Skip to content

Instantly share code, notes, and snippets.

@mauricioszabo
Created May 17, 2014 13:17
Show Gist options
  • Save mauricioszabo/a54a34a64da1612af73f to your computer and use it in GitHub Desktop.
Save mauricioszabo/a54a34a64da1612af73f to your computer and use it in GitHub Desktop.
Futures with Scala and Ruby
require 'java'
require 'scala-library.jar'
java_import 'scala.concurrent.Future'
java_import 'scala.concurrent.Await'
java_import 'scala.concurrent.ExecutionContext'
java_import 'scala.concurrent.duration.Duration'
module FutureSugar
java_import 'scala.Function1'
java_import 'scala.concurrent.ExecutionContext'
def flat_map(&block)
java_send :flatMap,
[Function1.java_class, ExecutionContext.java_class],
block,
ExecutionContext.global
end
def map(&block)
java_send :map,
[Function1.java_class, ExecutionContext.java_class],
block,
ExecutionContext.global
end
def self.apply(&block)
Future.apply(block, ExecutionContext.global).extend(self)
end
end
fusers = FutureSugar.apply do
sleep 10
[ { name: "Mauricio", login: "mauricio" },
{name: "Leo", login: "leo" } ]
end
finternet = FutureSugar.apply do
sleep 14
[ { age: 10, login: "mauricio" },
{age: 50, login: "leo" },
{age: 30, login: "foobar"} ]
end
result = fusers.flat_map do |list_users|
finternet.map do |list_internet|
list_users.flat_map do |user|
list_internet.flat_map do |internet|
if(user[:login] == internet[:login])
[user.merge(internet)]
else
[]
end
end
end
end
end
puts "Before being processed: #{result.value}"
processed = Await.result(result, Duration.create('20 seconds'))
puts "After being processed: #{result.value}"
puts "Result: #{processed}"
import concurrent._
import concurrent.duration._
import ExecutionContext.Implicits.global
object ScalaFutures extends App {
val fusers = findFromDB
val finternet = findFromInternet
val result = for(
list_users <- fusers;
list_internet <- finternet
) yield for(
user <- list_users;
internet <- list_internet;
if(user('login) == internet('login))
) yield user ++ internet
println("Before being processed: " + result.value)
val processed = Await.result(result, 20.seconds)
println("After being processed: " + result.value)
println("Result: " + processed)
def findFromDB = Future {
Thread sleep 10000 //10 seconds
List(
Map('name -> "Mauricio", 'login -> "mauricio"),
Map('name -> "Leo", 'login -> "leo")
)
}
def findFromInternet = Future {
Thread sleep 14000 //14 seconds
List(
Map('age -> 10, 'login -> "mauricio"),
Map('age -> 50, 'login -> "leo"),
Map('age -> 30, 'login -> "foobar")
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment