siman
3/28/2013 - 5:49 PM

IgnoreIfBusyTyped.scala

trait IgnoreIfBusyCmd

abstract class IgnoreIfBusyTyped[C <: IgnoreIfBusyCmd](implicit m: Manifest[C]) extends Actor with ActorLogging{

  import context.{become, unbecome}
  import context.system

  class Completed {
    override def toString = "Completed"
  }

  private val rightClass = m.erasure

  protected def receive: Receive = {
    case cmd: IgnoreIfBusyCmd if isCmdOfRightType(cmd) =>
      val completed = new Completed
      become {
        case `completed` => unbecome()
      }
      future(run(cmd.asInstanceOf[C]), completed)
    case x => log.warning("Unknown command received: " + x)
  }

  private def isCmdOfRightType[T <: IgnoreIfBusyCmd](cmd: T) = rightClass == cmd.getClass

  private def future[T](f: => T, completed: Completed) {
    Future(f).onComplete(_ => self ! completed)
  }

  protected def run(cmd: C)
}