Composing behaviors in Akka Typed

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.

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?

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
...

why not something like this:

Behaviors.receive { (context, message) =>
      
      // do something with each message here
      
      message match {
        case "hi" => ...
        case "hello" => ...
      }
}

For true cross cutting concerns a BehaviorInterceptor is nice (it can also access context).

1 Like