如何解释这个FSM示例的行为?

时间:2016-09-02 19:53:18

标签: scala akka fsm

我正在尝试理解akka FSM模式,在下面的示例中,我不明白为什么我没有得到与处理相对应的打印 - >完成。我的印刷清楚地表明我完整了。有人可以赐教吗?

import akka.actor.{ActorRef, FSM}
import scala.concurrent.duration._
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.FSM.Event
import akka.actor.Props

object FSM2 extends App{
  val system = ActorSystem("test")
  val test = system.actorOf(Props[Test], "t")
  test ! Set("hello")
}

sealed trait State
case object idle extends State
case object processing extends State
case object complete extends State

sealed trait Data
case class Content(processing:Int) extends Data

class Test extends FSM[State, Data]{

  when(idle) {
    case Event(test:Set[String], _) => {
      goto(processing) using Content(test.size-1)
    }
 }
  when(processing, stateTimeout = 1 second) {
     case Event(StateTimeout, Content(count)) => {
     println(count)
     count match {
        case 0 => goto(complete) using Content(0)
        case _ => stay using Content(count)
     }
    }
  }
  when (complete, stateTimeout = 1 second) {
    case Event(StateTimeout, _) => {
      println("in complete")
      goto(idle) using Content(0)
    }
 }

  onTransition({
    case idle -> processing => {
    println("idle -> processing")
  }
  case processing -> complete => {
      println("processing -> complete")
  }
  })

  startWith(idle, Content(0))
  initialize()
}
output:
idle -> processing
idle -> processing
0
idle -> processing
in complete
idle -> processing

I thought this would be the expected output:

idle -> processing
0
idle -> processing
processing -> complete
in complete
(go back to idle with no print)

我写的其他一些代码表明它不执行模式匹配而是执行赋值。

如果我在State对象上使用大写字母(空闲,处理,完成和空闲 - >处理等),它就有效。)

1 个答案:

答案 0 :(得分:3)

主要问题是,case idle -> processing与您的案例对象不匹配,但与任何事物相匹配,并将这些事件与名称idleprocessing绑定在一起。为了匹配这些case对象,你必须匹配一个稳定的标识符,这意味着要么用大写字母(正如你已经观察过的那样)启动case对象,要么在你的匹配中用反引号包围它们:

case `idle` -> `processing`

考虑到这一点,应该清楚的是,为每个状态转换打印字符串"idle -> processing",而不仅仅是从空闲到处理的字符串,您可以通过打印println(s"$idle -> $processing")来验证。< / p>

output:
idle -> processing // triggered by initialize(), is actually idle -> idle
idle -> processing // the actual idle -> processing transition
0
idle -> processing // processing -> complete
in complete
idle -> processing // complete -> idle