Forked from DanielaSfregola/eventStreamExample.scala
Created
November 15, 2017 16:01
-
-
Save homerquan/a744dc83ab5bd52649c2612e8ca5f548 to your computer and use it in GitHub Desktop.
An example on how to use an EventStream in Akka. See article http://danielasfregola.com/2015/04/20/peer-to-many-communication-in-akka/
This file contains hidden or 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._ | |
case class Book(title: String, authors: List[String]) | |
class BookPublisher extends Actor { | |
def receive = { | |
case book: Book => { | |
println(s"Yeah! Publishing a new book: $book") | |
context.system.eventStream.publish(book) | |
} | |
} | |
} | |
class BookSubscriber extends Actor { | |
override def preStart = context.system.eventStream.subscribe(self, classOf[Book]) | |
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 bookPublisher = system.actorOf(Props[BookPublisher], name = "book-publisher") | |
val subscriber1 = system.actorOf(Props[BookSubscriber], name = "subscriber-1") | |
val subscriber2 = system.actorOf(Props[BookSubscriber], name = "subscriber-2") | |
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)) | |
// My name is subscriber-2 and I have received a new book: Book(A book title,List(Author, Another author)) | |
system.eventStream.unsubscribe(subscriber2, classOf[Book]) | |
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-1 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