如何在我当前的设计中扩展akka接收方法

时间:2017-09-16 18:54:01

标签: scala akka

我有一个这样的演员:

class MyActor[T] extends Actor {
   def receive = {
      case Option1(t: T) =>
        doWork(t) onComplete .....
      case Option2 =>

   }

   def doWork(T): Future[T]{
   }
}

然后我有一个继承了上述的演员:

class OtherActor extends MyActor {
  val m = mutable.Map.empty[Int, User]
  override def doWork(..) = {
      //
  }
}

现在在我的OtherActor演员中我想为接收方法添加一些方法,我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以在Receive内的OuterActor块中定义其他行为,并使用orElse将该行为链接到其父级行为:

class OtherActor extends MyActor {
  val m = mutable.Map.empty[Int, User]
  override def doWork(...) = ???

  val otherBehavior: Receive = {
    case ...
  }

  override def receive = otherBehavior.orElse(super.receive)
}

这是可能的,因为Receive只是PartialFunction[Any, Unit]的类型别名。有关撰写演员行为的更多信息,请参见here

作为旁注,您应该更喜欢var m = immutable.Map.empty[Int, User]而不是val m = mutable.Map.empty[Int, User],以帮助避免暴露演员的状态,如answer中所述。