Home > database >  Can an Akka Actor Handle Multiple Message Types in Akka Typed
Can an Akka Actor Handle Multiple Message Types in Akka Typed

Time:03-28

Is it possible to handle multiple message types from a single actor.

For example, assume there is an actor called TradingStrategy that trades stocks. It takes in pricing data pumped in from another Actor. When it decides to place a trade, it sends a message to an another Actor, call it OrderActor, to place a trade. But the TradingStrategy Actor is interested in knowing whether or not the order placed was successful or rejected, etc... because it may change its strategy based on the results from the place order action. In this example, it seems the TradingStrategy needs to handle messages for pricing updates AND order updates. Is this possible with Akka typed? Are there ways to handle this situation?

Here is a code example: IEXData is the data message.

  def apply(orderActor: ActorRef[OrderCommand]): Behavior[IEXData] = Behaviors.setup { context =>
    new SimpleTradingStrategy(context, brokerActor)
  }
}

class SimpleTradingStrategy(
    context: ActorContext[IEXData],
    orderActor: ActorRef[OrderCommand],
    ticker: Ticker = "spy"
) extends AbstractBehavior[IEXData](context) {

CodePudding user response:

TradingStrategy's protocol would have to include messages indicating order updates. A TradingStrategy actor can register a message adapter which will translate the messages sent by the order actor into TradingStrategy's protocol: the TradingStrategy can present the "virtual" ActorRef returned by the message adapter to the order actor without the order actor knowing that its a TradingStrategy.

  • Related