Skip to content

Instantly share code, notes, and snippets.

@arkadius
Created March 24, 2016 19:59
Show Gist options
  • Save arkadius/2c40fd3d7d6148665061 to your computer and use it in GitHub Desktop.
Save arkadius/2c40fd3d7d6148665061 to your computer and use it in GitHub Desktop.
import akka.actor.{Actor, ActorSystem, Props, Stash}
import scala.concurrent._
object AsyncRestart extends App {
val system = ActorSystem()
val actor = system.actorOf(Props(new AsyncRestartActor))
actor ! "1"
actor ! "2"
actor ! "fail"
actor ! "3"
}
class AsyncRestartActor extends Actor with Stash {
import context.dispatcher
@scala.throws[Exception](classOf[Exception])
override def preStart(): Unit = {
init()
}
@scala.throws[Exception](classOf[Exception])
override def postRestart(reason: Throwable): Unit = {} // to avoid init before PreviousStopped
private def init(): Unit = {
Future {
blocking {
Thread.sleep(1000)
println("init done")
}
}.onComplete { _ =>
self ! Initialized
}
}
override def receive: Receive = {
case PreviousStopped =>
init()
case Initialized =>
unstashAll()
context.become(initialized)
case msg =>
stash()
}
private val initialized: Receive = {
case "fail" =>
throw new Exception("failed")
case msg =>
println(msg)
}
override def postStop(): Unit = {
Future {
blocking {
Thread.sleep(1000)
println("stop done")
}
}.onComplete { _ =>
self ! PreviousStopped
}
super.postStop()
}
}
case object Initialized
case object PreviousStopped
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment