簡體   English   中英

Scala akka 輸入:如何從它的實例獲取 ActorRef 到 Actor 並發送消息本身?

[英]Scala akka typed: how to get ActorRef to Actor from it's instance and send message itself?

我想將消息從 Actor 實例(案例類/類從它的行為創建)發送到它的 Actor。

我通過保存實例獲得它,然后將ActorRef保存在其中:

val (instance, behaviour) = MyActorInstance(Nothing)
val actor = ActorSystem(instance, "SomeName123")
//save it here
instance.setMyActor(actor)

object MyActorInstance {
  def apply(ctx: ActorContext[Commands]): (MyActorInstance,Behavior[Commands]) = {
    val actorInstance = new MyActorInstance(ctx)
    val behaviour: Behavior[Commands] =
      Behaviors.setup { context =>
        {
          Behaviors.receiveMessage { msg =>
            actorInstance.onMessage(msg)
          }
        }
      }
    (actorInstance,behaviour)
  }
}

class MyActorInstance(context: ActorContext[Commands]) extends AbstractBehavior[Commands](context) {

  protected var myActorRef: ActorRef[Commands] = null

  def setMyActor(actorRef: ActorRef[Commands]): Unit = {
    myActorRef = actorRef
  }

  override def onMessage(msg: Commands): Behavior[Commands] = {
    msg match {
      case SendMyself(msg) =>
        myActorRef ! IAmDone(msg)
        Behaviors.same
      case IAmDone(msg) =>
        println(s"Send $msg to myself!")
        Behaviors.same
    }
  }
}

在這里,我將ActorRef保存到 Actor,因為它是var myActorRef的實例。 然后我使用myActorRef通過SendMyself消息將消息從 Actor 的實例發送到自身。

但是,正如你看到的,我使用的變量,這是不好的:節省ActorRef它的需要重寫場myActorRef的實例MyActorInstance類從nullActorRef -這是可能只使用var iables。

如果我嘗試使用VAL並通過重寫它的實例對新創建不可變類,然后從舊到新的交換,我的演員actor依然與老實例,其中myActorRef == null

現在我找到了一種方法:只使用var而不是val或不可變類。

但我想使用 val 或什么都不使用。 為此,我需要從它的實例中獲取 ActorRef,但是如何?

沒有理由進行如此復雜的舞蹈,只需使用ctx.self 並且請在詢問之前至少閱讀最基本的文檔,它甚至可以節省您的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM