How to convert a class T object into a Future[T] object in akka

Viewed 937

I am trying to do something with akka and scala and i am new to it. I want to append the result of an 'Any' Future into one of the fields in the class

So i have class called T defined as

class T {
  var a: String =_
  var result = List[Any]= List()
}

Now i have a variable which receives a future value

var futureResult:Future[Any] = //receives a future value

in a function called addResult which takes an T object and returns a future T object.

def addResult(obj1:T):Future[T] ={
  var obj2:T = new T()
  obj2.a = obj1.a
  obj2.result = obj1.result
  //I want to append results of futureResult into obj2.result when it is completed
  // obj2.result = futureResult :: obj2.result

  return Future(obj2)
}

I have to finally call this function from a flow.

val b = Flow[T].mapAsync[T](1)(addResult(_))
2 Answers

You can change the commented line like this:

futureResult.map { res =>
  obj2.result = res :: obj2.result
  obj2
}

And then you won't need the last line.

First, as @riccardo.cardin noted using T as a name of a class is very bad idea, because of T usual points to generic. However, you can put any logic in Future with a simple closure, in your case, it looks like this:

Future {
 new T("some string", 1 :: 2 :: 3 :: Nil)
}

After that, you can combine asynchronous computation via flatMap, map or with for comprehensive or even use cats black magic with |@|:

for {
    f1 <- future1()
    f2 <- future2(f1.id)
} yield f2.name

(future1 |@| future2) map { _ - _ }

In your case this transformation depends from logic of your code.

Related