Scala Akka演员-获取演员的状态

时间:2018-11-20 20:33:45

标签: scala akka actor

import { NgModule } from "@angular/core"; import { Routes } from "@angular/router"; import { NativeScriptRouterModule } from "nativescript-angular/router"; const routes: Routes = [ { path: "", redirectTo: "/trainingunits", pathMatch: "full" }, { path: "trainingunits", loadChildren: "./trainingunit/list/trainingunit.module#TrainingUnitModule" } ]; @NgModule({ imports: [NativeScriptRouterModule.forRoot(routes)], exports: [NativeScriptRouterModule] }) export class AppRoutingModule { } 方法定义Akka演员中演员的行为。我正在寻找一种方法,该方法可以为演员提供最好在Scala运行时处理的所有不同消息(及其类型)。

1 个答案:

答案 0 :(得分:0)

直接回答

很遗憾,akka不具备您要的功能。 receive方法is defined as

type Receive = PartialFunction[Any, Unit]

abstract def receive : Actor.Receive

PartialFunction无法枚举它可以处理的所有类型。此外,将Actor实例化为ActorRef后,您将无权访问基础的receive方法。

一种选择是在Actor实现之外定义接收,然后使用isDefinedAt method of PartialFunction测试特定值:

object MyActor {
  val myPartial : Receive = {
    //receive functionality
  }
}

class MyActor extends Actor {
  override def receive : Receive = MyActor.myPartial
}

//test if a value can be processed by MyActor

val testValue = 42

val testValueIsDefined = MyActor.myPartial.isDefinedAt(testValue)

间接答案

如果您正确地组织了代码,那么问题的基础就变得不必要了。

我发现一种好的做法是严格声明Actor可以接收哪些类型的输入:

sealed trait MyActorInputs

case class Foo(value : Int) extends MyActorInputs
case class Bar(value : String) extends MyActorInputs

object MyActor {
  val processInput : MyActorInput => Unit = ???
}

class MyActor extends Actor {
  override def receive : Receive = {
    case input : MyActorInput => 
      MyActor.processInput(input)
    case unknown => 
      System.error.println(s"MyActor received unknown input: $unknown")
  }
}

此技术不提供编译器时间检查或严格保证,但是如果您在所有Actor中采用该技术,则它会使大型项目的工作变得更轻松。它还可以让您use reflection to dynamically get a list of available input types

相关问题