scala - How can I flatten this Future[T] structure? -


given following example:

  val handler : connection = new databaseconnectionhandler()   val result : future[future[future[option[resultset]]]] = handler.connect     .map( (parameters) => handler )     .map( connection => connection.sendquery("begin transaction serializable") )     .map( future => future.map( query => query.rows ) )     .map( future => handler.sendquery("commit").map( query => future ) ) 

is possible flatten receive future[option[resultset]] @ end instead of future inside future inside future structure in scala?

i using scala's 2.10 future's , promise's, can't find way to this. know can use nested callbacks rather avoid since code going horrible.

the connection trait defined here.

whenever map argument of type a => future[b] should using flatmap.

the code this:

  val connection : connection = new databaseconnectionhandler( defaultconfiguration )   val result: future[queryresult] = connection.connect     .flatmap( _ => connection.sendquery("begin transaction isolation level repeatable read") )     .flatmap( _ => connection.sendquery("select 0") )     .flatmap( _ => connection.sendquery("commit").map( value => query ) ) 

alternatively, use for-comprehension. it uses flatmap you.

val connection : connection = new databaseconnectionhandler( defaultconfiguration ) val result: future[queryresult] = {   _ <- connection.connect   _ <- connection.sendquery("begin transaction isolation level repeatable read")   _ <- connection.sendquery("select 0")   queryresult <- connection.sendquery("commit").map( value => query ) } yield { queryresult } 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -