Is the a way to internally monitor the transition

2019-06-26 04:26发布

Considering an FSM actor that starts at state Idle

startWith(Idle, IdleData)

I'd like to monitor the transition to this first state (from no state?)

I tried

onTransition {
    case _ -> Idle => // Wasn't called
}

According to the relevant FSM documentation:

It is also possible to pass a function object accepting two states to onTransition, in case your transition handling logic is implemented as a method:

onTransition(handler _)

def handler(from: StateType, to: StateType) {
  // handle it here ...
}

Given that the from type is StateType and not Option[StateType] I think that it may not be possible, but maybe I'm missing something.

标签: scala akka
1条回答
仙女界的扛把子
2楼-- · 2019-06-26 04:58

I was searching for something similar recently.

If I understand your question correctly, Here is one way to monitor when you start off your FSM from the initial state:

class ExampleFSM extends Actor with FSM[State, Data] {
  // A FSM begins its existence in Idle state and can move to different states
  startWith(Idle, NoData)

  when(Idle) {
    case Event(SetData(something), NoData) =>
      goto(SomeOtherState) using Data(something)
  }

  onTransition {
    case Idle -> Idle =>
      stateData match {
        case _ =>
          println("Initial transition")
      }
  }
}

In the above example, When We instantiate the FSM pass-in the message SetData(something), It starts at the state Idle and there is a transition that you can monitor which is Idle -> Idle.

In the above case when we start the FSM we can see an output Initial transition printed, you can leverage this to do more complex stuff as per your needs

So basically if you update your existing transition from case _ => Idle to case Idle -> Idle it should work

Note: There might be more than one way to do this, I am also still exploring the power of Akka FSM so my answer is just having one possible way of getting this.

查看更多
登录 后发表回答