swaheed swaheed - 11 months ago 92
Scala Question

how to use inner future value in outer future in scala

Hi I have two Futures FutureA and FutureB i want to take a value from FutureB and use it in FutureA but all i am getting is null
here is code

futureA = ask(ActorA, MessageA).mapTo[Int]
FutureB = ask(ActorB, MessageB).mapTo[Int]
var someResult=0

futureA.map {
result =>
FutureB.map { x =>
someResult=x//suppose it will retun 5
}
someResult=someResult+1//it should give 6
println(someResult)//here i am getting 1
}


I want
someResult
to return
6
but it is returning
1

how can I achieve that
I do not want to use blocking call
await.result

Answer Source

Dima's answer is absolutely correct. You're not assigning the result of FutureB.map so it's basically a side effect potentially executed in a background thread without your code knowing. You're likely to reach the print statement at runtime before the variable gets incremented, but maybe not, you can't know.

The right way of doing it is to use immutable variables and to chain your futures using flatMap/map.

Say you have a function called someFunction that takes two Ints and return a Result type : def someFunction(a: Int, b: Int): Result. You can then write the following code:

val result: Future[Result] =
  futureA.flatMap { a =>
    FutureB.map { b =>
      someFunction(a, b)
    }
  }

You can also write it using a for-comprehension which compile to exactly the same thing but is standard way of doing it:

val result: Future[Result] =
  for {
    a <- futureA
    b <- FutureB
  } yield someFunction(a, b)

Hope this answers your question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download