I have some events in my model and some handling logic. I want organize communication logic throw Actors. But how I can inherit handling logic without specifying act() in each concrete class
Simplified example
class Event {}
case class FooEvent(str : String) extends Event
case class BarEvent(i : java.lang.Integer) extends Event
trait FooListener extends Actor {
def act() {
react{
case FooEvent => print("foo received")
}
}
}
trait BarListener extends Actor {
def act() {
react{
case BarEvent => print("bar received")
}
}
}
class ListensOnlyBar extends BarListener{}
//can't be done:
//error: overriding method act in trait FooListener of type ()Unit;
//method act in trait BarListener of type ()Unit needs `override' modifier
//class ListensBarAndFoo extends FooListener with BarListener{
class ListensBarAndFoo extends FooListener with BarListener{}
react expects PartialFunction[Any, Unit] and you can nicely compose them together. Here is an example:
type Listener = PartialFunction[Any, Unit]
val foo: Listener = {
case FooEvent => print("foo received")
}
val bar: Listener = {
case BarEvent => print("bar received")
}
case class GenericListener(listener: Listener) extends Actor {
def act() {
react(listener)
}
}
GenericListener(bar)
GenericListener(foo orElse bar)
Related
I want to implement CRUD operation using akka actor. I am a new in akka so dont know the designing fundamentals of akka actors.
I want to share the behaviours of akka actors in multiple sub actors.
Fir example i want to save and delete student , teacher and other entity.
I have created actor for StudentDao.scala
class StudentDao extends Actor with ActorLogging{
override def Receive = {
case Add(student) =>
// Add to database
case Delete =>
//Delete from database
// Some other cases related to Student entity
}
}
case object StudentDao{
case class Add(user : Student)
case class Delete(id : String)
}
Same I have actor for TeacherDao.scala
class TeacherDao extends Actor with ActorLogging{
override def Receive = {
case Add(teacher) =>
// Add to database
case Delete =>
//Delete from database
// Some other cases related to teacher entity
}
}
object TeacherDao{
case class Add(user : teacher)
case class Delete(id : String)
}
I want to abstract delete method for both dao.
So i have create BaseDao.scala
class BaseDao extends Actor with ActorLogging{
override def Receive = {
case Delete =>
//Delete from database dao.delete
}
how can i abstract using base actor.
orElse is the way to extend actor behaviors, because an actor's Receive is simply an alias for PartialFunction[Any, Unit]. Below is a concrete illustration with your use case.
First, define the base behavior in a trait that must be mixed in with an actor. To avoid duplication, move the Delete case class into this trait's companion object.
trait BaseDao { this: Actor with ActorLogging =>
import BaseDao._
def baseBehavior: Receive = {
case Delete(id) =>
log.info(s"Deleting $id from db")
// delete from db
}
}
object BaseDao {
case class Delete(id: String)
}
Then, mix in the above trait into your other actors and chain the behaviors with orElse. Note that I created dummy Student and Teacher case classes so that this code would compile. StudentDao:
class StudentDao extends Actor with ActorLogging with BaseDao {
import StudentDao._
def studentBehavior: Receive = {
case Add(student) =>
log.info(s"Adding student: $student")
// some other cases related to Student
}
def receive = studentBehavior orElse baseBehavior
}
object StudentDao {
case class Add(user: Student)
}
case class Student(name: String)
And TeacherDao:
class TeacherDao extends Actor with ActorLogging with BaseDao {
import TeacherDao._
def teacherBehavior: Receive = {
case Add(teacher) =>
log.info(s"Adding teacher: $teacher")
// some other cases related to Teacher
}
def receive = teacherBehavior orElse baseBehavior
}
object TeacherDao {
case class Add(user: Teacher)
}
case class Teacher(name: String)
You can create a trait for the base actor, with a common receive function orElse another one that has to be implemented in sub actors:
trait BaseActor extends Actor {
override def receive: Receive = commonReceive orElse handleReceive
def commonReceive: Receive = {
case CommonMessage => // do something
}
def handleReceive: Receive
}
And then your sub actors only have to implement handleReceive:
class SubActor extends BaseActor {
override def handleReceive: Receive = {
case SpecificMessage => // do something
}
}
I have some class:
class MyActor extends Actor{
override def receive: Receive = {
case s: String => doSome()
case i: Int => //something else
}
}
object MyActor{
def doSome() = //some action
}
Is it an idiomatic way in Scala? I did that to simplify testing the Actor. I dont want to create ActorSystem and write integration test in my specific case.
Is it common to do so?
No, the idiomatic way is to extract those methods into a trait, and have the actor extend that trait:
trait DoSomething {
def doSome() = {
println("Doing something")
}
}
class MyActor extends Actor with DoSomething {
override def receive: Receive = {
case s: String => doSome()
case i: Int => //something else
}
}
I have a parent actor named "manager" which creates several child actors.
These child actors then send back their response via "sender tell", i.e directly back to "manager".
I want to create a unit test for this manager actor, and therefore need to inject a probe to forward the messages from the manager to its children.
I used the following post:
http://www.superloopy.io/articles/2013/injecting-akka-testprobe.html
However i'm still having some trouble getting this done correctly.
In order to simplify the situation, attached is code describing the actors and unit test i wrote for just one child.
Manager class:
trait ManagerChildProvider {
def createTimestampPointChild: Actor
}
trait ProductionManagerChildProvider extends ManagerChildProvider {
def createTimestampPointChild = new TimeDifferenceCalculationActor
}
object Manager {
def apply() = new Manager("cid1") with ProductionManagerChildProvider
}
class Manager(name: String) extends Actor with ActorLogging {
this: ManagerChildProvider =>
#Autowired private val modelParams = new ModelParams //list of parameters
val timeDifference = context.actorOf(Props(createTimestampPointChild))
def receive = {
case p#TimePoint(tPoint) =>
timeDifference ! p
case _ =>
log.error("Unknown message type")
}
}
Child class:
class TimeDifferenceCalculationActor extends Actor with ActorLogging {
var previousTimestamp: Long = -1
def receive = {
case tPoint(timestamp) =>
if (previousTimestamp != -1) {
sender ! Result(1)
}
case _ =>
log.error("Unknown message type")
}
}
Test class:
object BarSpec {
class Wrapper(target: ActorRef) extends Actor {
def receive = {
case x => target forward x
}
}
}
trait ChildrenProvider {
def newFoo: Actor
}
class BarSpec extends TestKitSpec("BarSpec") {
import Manager._
import BarSpec._
trait TestCase {
val probe = TestProbe()
trait TestChildrenProvider extends ManagerChildProvider {
def newBar = new Wrapper(probe.ref)
}
val actor = system.actorOf(Props(new Manager(componentId = "cid1") with TestChildrenProvider))
}
"Bar" should {
"involve child in doing something" in new TestCase {
actor ! tPoint(1)
actor ! tPoint(2)
probe.expectMsg(tPoint(1))
//probe.reply("ReplyFromChild")
//expectMsg("ReplyFromParent")
}
}
}
Additional test class:
abstract class TestKitSpec(name: String) extends TestKit(ActorSystem(name)) with MustMatchers with BeforeAndAfterAll with ImplicitSender with WordSpecLike{
override def afterAll() {
system.shutdown()
}
}
Currently i get the following errors:
Error:(36, 42) object creation impossible, since method > createTimestampPointChild in trait ManagerChildProvider of > type => akka.actor.Actor is not defined
val actor = system.actorOf(Props(new Manager(componentId = "cid1") with TestChildrenProvider))
Error:(11, 16) overriding method run in trait BeforeAndAfterAll of type > (testName: Option[String], args: > org.scalatest.Args)org.scalatest.Status;
method run in trait WordSpecLike of type (testName: Option[String], > args: org.scalatest.Args)org.scalatest.Status needs `abstract override' > modifiers
abstract class TestKitSpec(name: String) extends > TestKit(ActorSystem(name))
any help with these specific errors or with the task in general would be highly appreciated
Say I have the below:
type Receive = PartialFunction[Any, Unit]
trait Functionality {
/**
* A set containing all Receive functions
*/
var allReceives: Set[Receive] = Set[Receive]()
}
Now other trait's can extend Functionality and do awesome stuff. Example:
trait LoadBalancer extends Functionality{
def body:Receive = {
case ...
}
allReceives += body
}
And ultimately my class:
class Main with LoadBalancer with SecurityFunctionality
with OtherFunctionality with Functionality{
def receive = {
case x if allReceives.foldLeft(false) { (z, f) => if (f isDefinedAt x) { f(x); true } else z } == true => ()
}
def body: Receive = {
}
allReceives += body
}
Question: What I wish to do is, in Main I need to call body function of all the traits that I have inherited. This way my code can be loosely coupled and I can add/remove functionality at a go.
The above works, but I do not like it as the compiler cannot guarantee that any trait that extends Functionality should add its body to allReceives.
I cannot declare def body:Receive in Functionality as then my implementation in Main will override body implementations of other traits. I am sure there should be a smarter way!
On second thought, composition really might be a better option here. This is a simpler solution, without any funny "abstract override"s:
object Main {
type Receive = PartialFunction[Any, Unit]
trait Receiver {
def receive: Receive
}
class LoadBalancer extends Receiver {
override def receive: Receive = {
case "one" => println("LoadBalancer received one")
}
}
class OtherFunctionality extends Receiver {
override def receive: Receive = {
case "two" => println("OtherFunctionality received two")
}
}
class MainFunctionality extends Receiver {
override def receive: Receive = {
case "three" => println("MainFunctionality received three")
}
}
class CompositeReceiver(receivers: List[Receiver]) extends Receiver {
override def receive: Receive = {
case msg =>
receivers.find(_.receive.isDefinedAt(msg)) map (_.receive(msg))
}
}
def main(args: Array[String]) {
val main = new CompositeReceiver(List(new OtherFunctionality, new LoadBalancer, new MainFunctionality))
main.receive("one")
main.receive("two")
main.receive("three")
}
}
This does not really answer your question, but here is a solution using the stackable traits pattern. Alas you still need to call super.receive as the last case in each trait, but I could not find a way around that yet.
object Main {
type Receive = PartialFunction[Any, Unit]
trait Receiver {
def receive: Receive
}
trait LoadBalancer extends Receiver {
abstract override def receive: Receive = {
case "one" => println("LoadBalancer received one")
case msg => super.receive(msg)
}
}
trait OtherFunctionality extends Receiver {
abstract override def receive: Receive = {
case "two" => println("OtherFunctionality received two")
case msg => super.receive(msg)
}
}
class Main extends Receiver {
override def receive: Receive = {
case "three" => println("Main received three")
}
}
def main(args: Array[String]) {
val main = new Main with OtherFunctionality with LoadBalancer
main.receive("one")
main.receive("two")
main.receive("three")
}
}
Consider these two traits:
trait Poked extends Actor {
override def receive = {
case Poke(port, x) => ReceivePoke(port, x)
}
def ReceivePoke(port: String, x: Any)
}
trait Peeked extends Actor {
override def receive = {
case Peek(port) => ReceivePeek(port)
}
def ReceivePeek(port: String)
}
Now consider I can create a new Actor that implements both traits:
val peekedpoked = actorRef(new Actor extends Poked with Peeked)
How do I compose the receive handlers? i.e., the receiver should be something like the following code, though "automatically generated" (i.e., all traits should compose):
def receive = (Poked.receive: Receive) orElse (Peeked.receive: Receive) orElse ...
You can use super[T] to reference members of particular super classes/traits.
For example:
trait IntActor extends Actor {
def receive = {
case i: Int => println("Int!")
}
}
trait StringActor extends Actor {
def receive = {
case s: String => println("String!")
}
}
class IntOrString extends Actor with IntActor with StringActor {
override def receive = super[IntActor].receive orElse super[StringActor].receive
}
val a = actorOf[IntOrString].start
a ! 5 //prints Int!
a ! "Hello" //prints String!
Edit:
In response to Hugo's comment, here's a solution that allows you to compose the mixins without having to manually wire their receives together. Essentially it involves a base trait with a mutable List[Receive], and each mixed-in trait calls a method to add its own receive to the list.
trait ComposableActor extends Actor {
private var receives: List[Receive] = List()
protected def registerReceive(receive: Receive) {
receives = receive :: receives
}
def receive = receives reduce {_ orElse _}
}
trait IntActor extends ComposableActor {
registerReceive {
case i: Int => println("Int!")
}
}
trait StringActor extends ComposableActor {
registerReceive {
case s: String => println("String!")
}
}
val a = actorOf(new ComposableActor with IntActor with StringActor).start
a ! 5 //prints Int!
a ! "test" //prints String!
The only thing to keep in mind is that the order of the receives should not be important, since you won't be able to easily predict which one is first in the chain, though you could solve that by using a mutable hashmap instead of a list.
You can use empty Receive in base actor class and chain receives in their definitions.
Sample for Akka 2.0-M2:
import akka.actor.Actor
import akka.actor.Props
import akka.event.Logging
import akka.actor.ActorSystem
class Logger extends Actor {
val log = Logging(context.system, this)
override def receive = new Receive {
def apply(any: Any) = {}
def isDefinedAt(any: Any) = false
}
}
trait Errors extends Logger {
override def receive = super.receive orElse {
case "error" => log.info("received error")
}
}
trait Warns extends Logger {
override def receive = super.receive orElse {
case "warn" => log.info("received warn")
}
}
object Main extends App {
val system = ActorSystem("mysystem")
val actor = system.actorOf(Props(new Logger with Errors with Warns), name = "logger")
actor ! "error"
actor ! "warn"
}