Using For Comprehension for async callbacks?

125 views
Skip to first unread message

Vincent Marquez

unread,
Mar 21, 2012, 2:29:15 PM3/21/12
to scala...@googlegroups.com
Hello everyone, 

I've written SIP server and library in Scala and like in any network/server type code, in a lot of places i'm having to write nested callbacks which can look quite ugly: 

obj.connect( "some parameters", ()=> 
    obj2.connect("more parameters"), ()=>
         obj3.connect("even more"), ()=> 
               println("everone connceted"))))

so it occurred to me I could (arguably) make it a bit neater by using for comprehension.  Then it occurred to me there may already be an idiomatic "scala" way of doing this, and I shouldn't reinvent the wheel if so.   

Here's what I whipped up as an example of the kind of thing I want to do.  Obviously, instead of a sleep I'd be actually sending the whole method off to an actor which would do some stuff, and the callback would occur in another thread... 

http://pastebin.com/4Vy2SKmH

Too much abstraction?  Beautiful code?  Akka already has this? :-)  Thanks in advance!

--Vincent

Vlad Patryshev

unread,
Mar 21, 2012, 2:41:08 PM3/21/12
to Vincent Marquez, scala...@googlegroups.com
Goo idea. I believe this is how it should be.

-Vlad

√iktor Ҡlang

unread,
Mar 21, 2012, 3:18:39 PM3/21/12
to Vincent Marquez, scala...@googlegroups.com
import akka.dispatch._
import akka.dispatch.Future._

val result = flow {
  val f1: Future[Long] = someCalcReturningFuture
  val f2: Future[Long] = someOtherCalcReturningFuture
  f1() + f2()
}

or

val f1: Future[Long] = someCalcReturningFuture
val f2: Future[Long] = someOtherCalcReturningFuture

val result = for(v1 <- f1; v2 <- f2) yield v1 + v2

Cheers,
--
Viktor Klang

Akka Tech Lead
Typesafe - The software stack for applications that scale

Twitter: @viktorklang

Reply all
Reply to author
Forward
0 new messages