-1

I have funtion which is calling computeParallel() function which is calling 3 Futures F1,F2,F3 and returning String as return type.

def computeParallel():String =
{

      val f1 = Future {  "ss" }
      val f2 = Future { "sss" }
      val f3 = Future { "ssss" }

      val result: Future[String] = for {
        r1 <- f1
        r2 <- f2
        r3 <- f3
      } yield (r1 + r2 + r3)

    Await.result(result,scala.concurrent.duration.Duration.Inf)



} 

Using Await to collect the Aggregated Results.But People are saying usage of Await is Bad way of coding.

So i have used below one.Which is returning the Unit type.

        result.onComplete {
          case Success(res) => return res
        }

So if return Unit i cannot print anything.

can any help us.Is there anyother way to solve the problem

Thanks in Advance

Learnis
  • 526
  • 5
  • 25

1 Answers1

2

If computeParallel must return String you have to Await.result.

"Good way of coding" is to work with futures as soon as you get into them.

def computeParallel(): Future[String] = {
  val f1 = Future {  "ss" }
  val f2 = Future { "sss" }
  val f3 = Future { "ssss" }

  for {
    r1 <- f1
    r2 <- f2
    r3 <- f3
  } yield (r1 + r2 + r3)
} 

computeParallel().map(result => ???)

return normally shouldn't be used in Scala.

onComplete won't help because it

runs on some arbitrary (unspecified) thread ...

and we don't block until it completes.

Difference between Await.result and futures.onComplete in Scala

Promise can be completed to future so again you'll have Future[String] rather than String.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • Thanks, If i used .map() or Oncomplete im not getting any result. if i try to print something with these functions it is like "List()" printed and exited from the runtime – Learnis Sep 19 '19 at 04:24
  • If i had to mention the Thread.sleep() . Im not sure how much time it will execute exactly. – Learnis Sep 19 '19 at 04:27
  • @Learnis Regarding `map` I can't answer, you didn't write your code with `map`. Regarding `Oncomplete` I already said that callback runs on a different thread and `computeParallel` finishes before. – Dmytro Mitin Sep 19 '19 at 08:13
  • @Learnis `Thread.sleep()` is blocking as well as `Await.result` is blocking – Dmytro Mitin Sep 19 '19 at 08:56