Scala Future with Option() -
i'm creating 3 actor tasks using future, , trying collect 3 when finished. current code following:
implicit val timeout = timeout(5.seconds) val result1 = actor1 ? dataforactor(data) val result2 = actor2 ? dataforactor(data) val result3 = actor3 ? dataforactor(data) val answer = { <- result1.mapto[list[resultdata]] b <- result2.mapto[list[resultdata]] c <- result3.mapto[list[resultdata]] } yield (a ++ b ++ c).sorted answer oncomplete { case success(resultdata) => log.debug("all actors completed succesffully") successactor ! successdata(resultdata.take(2)) case failure(resultdata) => log.info("actors failed") }
each of actors (actor1, actor2, actor3) manipulates data , returns either none or option(list(resultdata)), shown in following code:
val resultdata = if(data.size == 0) none else { data.map { ... try { ... //manipulation on resultdata option(resultdata) } catch { case e: exception => none } }.flatten }
the statement concatenates lists each actor, , produces long list(resultdata).
i want in case 1 actor returns none, it's result in statement not add concatenation, i.e. list().
an example:
if get: result1 = list(1, 2, 3), result2 = none, result3 = list(4, 5),
i want: resultdata = list(1, 2, 3, 4, 5)
you replace none
nil
before mapto
way:
result1.map{ case none => nil case x => x }.mapto[list[resultdata]]
note should avoid mapto
generic type list
:
future("x" :: nil).mapto[list[int]] // res0: scala.concurrent.future[list[int]] future("x" :: nil).mapto[list[int]] foreach { _.map( _ + 1 ) } // java.lang.classcastexception: java.lang.string cannot cast java.lang.integer
because of type erasure mapto
can't prove have list of int
, not list
of other type. you'll same problem case l: list[int]
in receive
method of actor.
you should create special class messages this:
sealed trait resultlist { def data: list[resultdata] } case class notemptyresult(data: list[resultdata]) extends resultlist case object emptyresult extends resultlist { def data: list[resultdata] = nil } result1.mapto[resultlist]
Comments
Post a Comment