3

Lately I've found myself wrapping actors in classes so that I get back a little of the typesafety I lose when dealing with ActorRefs. The problem is, at the end, that not only I need to send a specific message, I also need to cast the response to the expected result. So I thought that I could send messages to actors that contain Promise so that they could report the result eventually.

Is that a bad idea? It looks pretty neat to me... Is typesafe and works just as good. Why hasn't anyone come with the idea? Is there anything wrong with it that I haven't noticed?

ask pattern based solution

case class GetUser(id:Long)

(actorRef ! GetUser(1l)).mapTo[User]

class UserRepoActor extends Actor{
  def receive={
   case GetUser(id)=>
     sender() ! getUser(id)
  }

  ...
}

Promise based solution

case class GetUser(id: Long, resp: Promise[User])

val req = GetUser(1l,Promise())
actorRef ! req
req.resp.future // No casting!!

class UserRepoActor extends Actor{
  def receive={
   case GetUser(id,resp)=>
     response.success(getUser(id))
  }

  ...
}
caeus
  • 3,084
  • 1
  • 22
  • 36
  • What do you mean by sending messages to Actor's that contain Promises? In any case, you have to pattern match on the incoming message. Can you post some code samples? – joesan Dec 19 '17 at 08:19

3 Answers3

1

There is nothing wrong. Very close approach is used in akka typed with the only difference: a single-use ActorRef[T] is being sent instead of Promise[T]

Odomontois
  • 15,918
  • 2
  • 36
  • 71
1

Promises won't work in distributed actor system.

At least, without additional efforts for that.

dveim
  • 3,381
  • 2
  • 21
  • 31
1

Ask pattern is definitely better.

1) Actors are supposed to share no state and interact with the outer world via messages. Fulfilling the promise is actually a mutating shared variable

2) Passing the stateful objects into actor's creator (e.g. promise) breaks actor's lifecycle in case of restarts

So promise-based approach works in simple cases. But if you use it just like that probably you don't need such complicated stuff like akka at all?

simpadjo
  • 3,947
  • 1
  • 13
  • 38
  • Not entirely true. The more complex a solution is, the more it can make use of typesafety. At the end the promise-base solutions is just there to add typesafety. I get by the other two proposed solutions that if I want to use distributed systems, promise-based solution will fail, and that Akka is actually striving to add some typesafety in a similar fashion. – caeus Dec 20 '17 at 10:04
  • By passing a stateful object to an actor you workaround inconvenience of akka API but violate akka ideology. From my point of view it is a bigger evil. Not only in case of distributed systems as I pointed. – simpadjo Dec 20 '17 at 11:01