Search code examples
scalaakkaakka-typed

How to implement the lifecycle PostStop?


I have the an actor, that the implementation looks as the following:

  def create(fsm: ActorRef[ServerHealth], cancel: Option[Cancellable]): Behavior[ServerHealthStreamer] =
    Behaviors.setup { context =>
      implicit val system = context.system
      implicit val materializer = ActorMaterializer()
      implicit val dispatcher = materializer.executionContext

      val kafkaServer = system
        .settings
        .config
        .getConfig("kafka")
        .getString("servers")

      val sink: Sink[ServerHealth, NotUsed] = ActorSink.actorRefWithAck[ServerHealth, ServerHealthStreamer, Ack](
        ref = context.self,
        onCompleteMessage = Complete,
        onFailureMessage = Fail.apply,
        messageAdapter = Message.apply,
        onInitMessage = Init.apply,
        ackMessage = Ack)

      val cancel = Source.tick(1.seconds, 15.seconds, NotUsed)
        .flatMapConcat(_ => Source.fromFuture(health(kafkaServer)))
        .map {
          case true =>
            KafkaActive
          case false =>
            KafkaInactive
        }
        .to(sink)
        .run()

      Behaviors.receiveMessage {
        case Init(ackTo) =>
          ackTo ! Ack
          Behaviors.same
        case Message(ackTo, msg) =>
          fsm ! msg
          ackTo ! Ack
          create(fsm, Some(cancel))
        case Complete =>
          Behaviors.same
        case Fail(_) =>
          fsm ! KafkaInactive
          Behaviors.same
      }
    }

As you can see, I am using akka typed and I have a question about implementing PostStop lifecycle.

How to implement lifecycle hooks in akka typed?

What am I trying to archive is, when the actor receives the message PostStop, then the stream will be canceled.


Solution

  • An actor in Akka Typed is notified of actor lifecycle events as 'signals', in this case the PostStop signal.