Skip to content

Instantly share code, notes, and snippets.

@davidkuster
Last active November 4, 2015 00:06
Show Gist options
  • Save davidkuster/7807ac312418ceb0b9f1 to your computer and use it in GitHub Desktop.
Save davidkuster/7807ac312418ceb0b9f1 to your computer and use it in GitHub Desktop.
Wrapping Scala (Akka) Futures with Grails Promises. A very common use case. :)
import grails.async.Promise
import grails.async.Promises
import scala.concurrent.Future
import akka.dispatch.Futures
import akka.dispatch.OnComplete
import java.util.concurrent.Callable
def actorSystem = ctx.getBean('actorSystem')
def dispatcher = actorSystem.dispatcher()
// create Grails Promise
Promise p = Promises.createPromise()
p.onComplete {
println "Grails Promise completed successfully"
}
p.onError {
println "Grails Promise errored out"
}
// create Scala Future
Future f = Futures.future(new Callable<String>() {
public String call() {
'Scala Future Value'
}
}, dispatcher)
// when we complete the Scala Future, tell it to complete the Grails Promise too
f.onComplete([onComplete: { throwable, result ->
p.accept('Grails Promise Value')
println "Scala Future = $result"
}] as OnComplete,
dispatcher)
println "Grails Promise = ${p.get()}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment