如何在Scala中正确使用Akka演员 [英] How to properly use akka actors in scala
本文介绍了如何在Scala中正确使用Akka演员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对演员的想法比较陌生,想知道我是否可以对自己的工作提出一些批评。对于项目的一部分,我需要有一个演员来告诉听众的演员时间。侦听演员必须能够添加到该演员中。
I'm relatively new to the idea of actors, and was wondering if I could get some critique on what I am doing. For part of a project, I need to have an actor that tells a collection of listening actors the time. The listening actors must be able to be added to this actor.
当前我有这个:
import akka.actor.Actor;
import akka.actor.ActorRef;
import com.github.nscala_time.time.Imports._;
class TimeManager extends Actor {
var actors:List[ActorRef] = List();
def receive = {
case AdvanceTime() => actors foreach (_ ! DateTime.now)
case AddListener(x) => actors = x :: actors
}
}
有什么办法我可以从此代码中删除状态(变量参与者)以使其更具功能性吗?
Is there any way that I can remove the state (var actors) from this code to make it more functional?
推荐答案
您无法删除状态,因为 TimeManager
应包含以下内容的列表:演员。
You can't remove state since TimeManager
should contain list of actors.
您可以隐藏它:
class TimeManager extends Actor {
def receive = getBehavior(Nil)
def getBehavior(actors: List[ActorRef]): Receive = {
case AdvanceTime() => actors foreach (_ ! DateTime.now)
case AddListener(x) => context become getBehavior(x :: actors)
}
}
这篇关于如何在Scala中正确使用Akka演员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文