Using Futures in Akka Actors

前端 未结 3 1142
无人共我
无人共我 2021-02-02 17:06

I\'m just starting to learn Akka Actors in Scala. My understanding is that messages received by an Actor are queued in an Actor\'s mailbox, and processed one at a time. By pro

3条回答
  •  故里飘歌
    2021-02-02 17:10

    The safest way to use futures within an actor is to only ever use pipeTo on the future and send its result as a message to an actor (possibly the same actor).

    import akka.pattern.pipe
    
    object MyActor {
    
      def doItAsynchronously(implicit ec: ExecutionContext): Future[DoItResult] = { 
      /* ... */ 
      }
    
    }
    
    class MyActor extends Actor {
    
      import MyActor._    
      import context.dispatcher  
    
      def receive = {
        case DoIt =>
          doItAsynchronously.pipeTo(self)
        case DoItResult =>
           // Got a result from doing it
      }
    
    }
    

    This ensures that you won't mutate any state within the actor.

提交回复
热议问题