learning scala akka ask_pattern
package com.example import akka.actor._ import akka.util.Timeout object Tutorial_03_Ask_Pattern extends App { val system = ActorSystem("DonutStoreActorySystem") val donutInfoActor = system.actorOf(Props[DonutInfoActor], name="DonutInfoActor") import DonutStoreProtocal._ import akka.pattern._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ implicit val timeout = Timeout(5 second) val vanillaDonutFound = donutInfoActor ? Info("vanilla") for { found <- vanillaDonutFound } yield (println(s"Vanilla donut found = $found")) val glazedDountFound = donutInfoActor ? Info("glazed") for { found <- glazedDountFound } yield (println(s"Glazed donut found = $found")) Thread.sleep(5000) system.terminate(); object DonutStoreProtocal{ case class Info(name: String) } class DonutInfoActor extends Actor with ActorLogging { import Tutorial_03_Ask_Pattern.DonutStoreProtocal._ override def receive: Receive = { case Info(name) if name == "vanilla" => log.info(s"Found valid $name donut") sender ! true case Info(name) => log.info(s"$name donut is not supported") sender ! false } } }
result:
Vanilla donut found = true [INFO] [08/23/2019 16:37:51.502] [DonutStoreActorySystem-akka.actor.default-dispatcher-5] [akka://DonutStoreActorySystem/user/DonutInfoActor] Found valid vanilla donut Glazed donut found = false [INFO] [08/23/2019 16:37:51.512] [DonutStoreActorySystem-akka.actor.default-dispatcher-5] [akka://DonutStoreActorySystem/user/DonutInfoActor] glazed donut is not supported