Writing a circuit (wire) using akka

311 views Asked by At

I am working on a Logic Circuit implementation with scala using akka and I need to implement a wire Actor (for example for an component actor such as an AND gate) : The wire should transport a signal, true or false.

1

There are 1 answers

0
Akos Krivachy On

It's great that you're learning akka, the task is a good place to start.

A couple of things before we start - your current code and modelling may be questioned in a few places.

  1. Why does AddComponent need a wireName? Do you plan to find wires by their actor name? Usually we use ActorRefs instead of their names.
  2. Also why does StateChange need a wireName? Does it really matter? I would say state propagation could be done using simple messages: StateChanged(state: Boolean)
  3. I don't think there's any benefit in storing names of actors since a set of their ActorRefs is fine.
  4. It's not usually a good idea to just handle primitive types like current: Boolean, we like to give semantic meaning to our messages as you did with StateChange so I would use that here also.

Some code I came up with:

import akka.actor.{ActorLogging, Actor, ActorRef}

case class AddComponent(actor: ActorRef)
case class StateChange(state: Boolean)

class Wire(var currentState: Boolean) extends Actor with ActorLogging {
  var connections = Set.empty[ActorRef]

  def receive: Actor.Receive = {
    case AddComponent(actor) =>
      connections += actor

    case StateChange(state) =>
      currentState = state
      val connectionsToPropagateTo = connections - sender // Don't propagate back to sender
      connectionsToPropagateTo.foreach { component =>
        component ! StateChange(currentState) // Send the component a StateChange message.
      }
  }
}

You can simply extend this with RemoveComponent and other stuff as needed.