Skip to content

Instantly share code, notes, and snippets.

@shishkin
Created January 3, 2014 22:31
Show Gist options
  • Save shishkin/8247957 to your computer and use it in GitHub Desktop.
Save shishkin/8247957 to your computer and use it in GitHub Desktop.
Helper method for akka actor system to keep asking an underlying `service` actor continuously and replying to the original requester upon the underlying request completion.
import akka.actor._
import akka.pattern.ask
import scala.concurrent.duration._
import scala.concurrent.Future
import scala.concurrent.Promise
import scala.concurrent.ExecutionContext
class AskingActor(val service: ActorRef) extends Actor {
case class SomeCommand(id: String)
case class SomeEvent(id: String)
case class ServiceRequest(foo: String)
import context._
def receive: Receive = {
case SomeCommand(id) =>
val replyTo = sender
keepAsking(service, ServiceRequest("bar"), 50.millis) foreach { replyTo ! SomeEvent(id) }
}
def keepAsking(recepient: ActorRef, msg: Any, every: FiniteDuration = 100.millis): Future[Any] = {
val p = Promise[Any]()
val cancel = system.scheduler.schedule(0.millis, every) {
ask(recepient, msg)(1.hour) foreach { reply => p.trySuccess(reply) }
}
val f = p.future
f.onComplete { reply => cancel.cancel() }
f
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment