Composing behaviors in Akka Typed

akka-typed

(Christopher Hunt) #1

Given the declaration of an Akka Typed behavior, is it possible to chain another behavior such that I can perform some processing for every message that comes in? I went looking for an andThen operator on the behavior but of course, didn’t find one.

My use case is that I have implemented my own keep-alive mechanism. When a message comes in, I wish to reset the keep-alive timer. I can do this for each message explicitly, but I was hoping I could keep my code to a minimum.


(Christopher Hunt) #2

Actually, what I am doing right now is to use setup as per:

Behaviors.setup { _ =>
  setPingReqTimer()

  Behaviors
    .receivePartial[Event] {

Thus, for any message received in this behavior, the time is reset.

Are there any better ways to achieve my use-case?


(Christopher Hunt) #3

OK, I believe I’ve figured it out… setup will only be executed the first time the actor is setup.

So, with each behavior that I have, instead of returning Behavior.same, I need to cause the invocation of the behavior again:

  def serverConnected(data: ConnAckReceived): Behavior[Event] = Behaviors.withTimers { timer =>
    if (data.keepAlive.toMillis > 0)
      timer.startSingleTimer("send-pingreq", SendPingReqTimeout, data.keepAlive)
...
   Behaviors
      .receivePartial[Event] {
 ...
        case (_, SendPingReqTimeout) =>
          data.remote.offer(ForwardPingReq)
          serverConnected(data) // Instead of Behaviors.same... which I guess makes sense as it isn't the same
...