Commit be5e9abf authored by h2b's avatar h2b

Convenience subscriber class added.

parent b82e5ec7
/*
SimGraf - A Simple Scala Graphics Library
Copyright 2016-2017 Hans-Hermann Bode
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.h2b.scala.lib.simgraf.event
import akka.actor.{ Actor, ActorRef, Props }
import de.h2b.scala.lib.util.{ Level, Logger }
/**
* Provides an actor subscribing to `Event`s received from the package object's
* global event stream.
*
* @since 1.2.0
* @author h2b
*/
class Subscriber private (val handler: PartialFunction[Event, Unit]) extends Actor {
override def preStart = stream.subscribe(self, classOf[Event])
private val log = Logger(getClass) at Level.Warn
def receive = {
case e: Event
log.debug(s"event received: $e")
handler(e)
case unknown
log.warn(s"unknown message received: $unknown")
}
}
object Subscriber {
/**
* @param handler partial function handling received events
* @return a reference to a new subscriber
*/
def ref (handler: PartialFunction[Event, Unit]): ActorRef =
system.actorOf(Props(new Subscriber(handler)))
}
......@@ -19,11 +19,10 @@ package de.h2b.scala.lib.simgraf.demo
import scala.util.Random
import akka.actor.{ Actor, Props }
import de.h2b.scala.lib.simgraf.event.{ Event, KeyEvent, MouseEvent, stream, system }
import de.h2b.scala.lib.simgraf.{ Color, Point, World }
import de.h2b.scala.lib.simgraf.event.{ Event, Subscriber }
import de.h2b.scala.lib.simgraf.layout.GridLayout
import de.h2b.scala.lib.simgraf.shapes.{ Coloring, Rectangle }
import de.h2b.scala.lib.simgraf.{ Color, Point, World }
object EventEchoDemo extends App {
......@@ -34,13 +33,8 @@ object EventEchoDemo extends App {
world.fill(Coloring(_ =>
Color(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))))
class EventSubscriber extends Actor {
override def preStart = stream.subscribe(self, classOf[Event])
def receive = {
case e: Event println(e)
}
Subscriber.ref {
case e: Event println(e)
}
system.actorOf(Props[EventSubscriber])
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment