目前,我有一个接收一些消息的actor,并将此消息的内容保存到可变的类级变量中:
class MyActor extends Actor { val items1: Seq[Item] = _ val items2: Seq[Item] = _ def receive = { case Start(items1, items2) => items1= items1 items2 = items2 case Result(...) => ... } private def method1(args...) = { // do something with items1 and items2 } private def method2(args...) = { // do something with items1 and items2 } }我读到,创建几个receive函数并使用context.become / unbecome来处理不同的状态真的很棒。 所以在我的情况下,我可以使用这样的receive函数:
def running(items1: Seq[Item], items2: Seq[Item]): Receive = { case Result(...) => ... } val waiting: Receive = { case Start(items1, items2) => context.become(running(items1, items2)) start( ) }这种方法在我看来非常清楚和好看,但问题是我有其他方法( method1和method2 )需要这个items2和items2变量。 我想到的唯一可能的解决方法是将items2和items2作为函数传递给method1和method2 ,但是这个方法已经有2-3个参数,并且向它们添加更多参数将使它们难以阅读(实际上我有2个以上方法)。
那么,在这种情况下Akka有任何模式吗? 或者拥有类级别的var是非常“合法的”(如我的第一个例子)?
Currently, I have an actor that receives some message and saves this message's content to mutable class-level variables:
class MyActor extends Actor { val items1: Seq[Item] = _ val items2: Seq[Item] = _ def receive = { case Start(items1, items2) => items1= items1 items2 = items2 case Result(...) => ... } private def method1(args...) = { // do something with items1 and items2 } private def method2(args...) = { // do something with items1 and items2 } }And I read that it's really good to create several receive functions and use context.become / unbecome to handle different states. So in my case I can use receive function like this:
def running(items1: Seq[Item], items2: Seq[Item]): Receive = { case Result(...) => ... } val waiting: Receive = { case Start(items1, items2) => context.become(running(items1, items2)) start( ) }This approach looks to me very clear and nice, BUT the problem is that I have other methods (method1 and method2) which need this items1 and items2 variables. The only possible workaround I think of is to pass items1 and items2 to method1 and method2 as a function, but this method already has 2-3 arguments, and adding more arguments to them will make them difficult to read (actually I have more than 2 methods).
So, is there any pattern in Akka for such cases? Or it's pretty 'legal' to have class-level vars (as in my first example)?
最满意答案
So, is there any patterns in Akka for such cases?我不知道。
Or it's pretty 'legal' to have class-level vars (as in my first example)?只要你没有从闭包或未来访问它们,就可以在actor内部使用var 。
但是,我建议您选择参数解决方案。 如果您的参数列表变得很长,您可以考虑将它们分组到case class es中。
So, is there any patterns in Akka for such cases?I am not aware of any.
Or it's pretty 'legal' to have class-level vars (as in my first example)?It is Ok to have var inside actors, as long you don't access them from closures or futures.
However, I'd recommend that you go for the argument solution. If your arguments list became very long, you may consider grouping them in case classes.
更多推荐
发布评论