Forked from DanielaSfregola/customEventBusExample.scala
Created
August 14, 2017 10:42
-
-
Save batakpout/412c81d257dacf79bb69a3bdbf07b7d1 to your computer and use it in GitHub Desktop.
An example on how to customize an Event Bus in Akka. See article http://danielasfregola.com/2015/04/20/peer-to-many-communication-in-akka/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.actor._ | |
import akka.event.{LookupClassification, EventBus} | |
import akka.event.ActorEventBus | |
case class Book(title: String, authors: List[String]) | |
class AuthorBookBus(author: String) extends EventBus | |
with LookupClassification | |
with ActorEventBus { | |
type Event = Book | |
type Classifier = Boolean | |
override def mapSize = 2 | |
override def classify(book: Book) = book.authors.contains(author) | |
override protected def publish(book: Book, subscriber: Subscriber)= subscriber ! book | |
} | |
class BookPublisher(bus: AuthorBookBus) extends Actor { | |
def receive = { | |
case book: Book => { | |
println(s"Yeah! Publishing a new book: $book") | |
bus.publish(book) | |
} | |
} | |
} | |
class BookSubscriber extends Actor { | |
def receive = { | |
case book: Book => println(s"My name is ${self.path.name} and I have received a new book: $book") | |
} | |
} | |
object Main extends App { | |
implicit val system = ActorSystem("publisher-subscribers-example") | |
val author = "Author" | |
val authorBookBus = new AuthorBookBus(author) | |
val bookPublisher = system.actorOf(Props(new BookPublisher(authorBookBus)), name = "book-publisher") | |
val subscriber1 = system.actorOf(Props[BookSubscriber], name = "subscriber-1") | |
val subscriber2 = system.actorOf(Props[BookSubscriber], name = "subscriber-2") | |
authorBookBus.subscribe(subscriber1, true) | |
authorBookBus.subscribe(subscriber2, false) | |
bookPublisher ! Book(title = "A book title", authors = List(author, "Another Author")) | |
// Yeah! Publishing a new book: Book(A book title,List(Author, Another Author)) | |
// My name is subscriber-1 and I have received a new book: Book(A book title,List(Author, Another Author)) | |
bookPublisher ! Book(title = "Another book title", authors = List("Another Author")) | |
// Yeah! Publishing a new book: Book(Another book title,List(Another Author)) | |
// My name is subscriber-2 and I have received a new book: Book(Another book title,List(Another Author)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment