Advertisement
Guest User

Untitled

a guest
May 28th, 2015
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. import akka.actor._
  2.  
  3. case class Book(title: String, authors: List[String])
  4.  
  5. class BookPublisher extends Actor {
  6.  
  7. def receive = {
  8. case book: Book => {
  9. println(s"Yeah! Publishing a new book: $book")
  10. context.system.eventStream.publish(book)
  11. }
  12. }
  13.  
  14. }
  15.  
  16. class BookSubscriber extends Actor {
  17.  
  18. override def preStart = context.system.eventStream.subscribe(self, classOf[Book])
  19.  
  20. def receive = {
  21. case book: Book => println(s"My name is ${self.path.name} and I have received a new book: $book")
  22. }
  23. }
  24.  
  25. object Main extends App {
  26.  
  27. implicit val system = ActorSystem("publisher-subscribers-example")
  28.  
  29. val author = "Author"
  30.  
  31. val bookPublisher = system.actorOf(Props[BookPublisher], name = "book-publisher")
  32.  
  33. val subscriber1 = system.actorOf(Props[BookSubscriber], name = "subscriber-1")
  34. val subscriber2 = system.actorOf(Props[BookSubscriber], name = "subscriber-2")
  35.  
  36. bookPublisher ! Book(title = "A book title", authors = List(author, "Another author"))
  37. // Yeah! Publishing a new book: Book(A book title,List(Author, Another author))
  38. // My name is subscriber-1 and I have received a new book: Book(A book title,List(Author, Another author))
  39. // My name is subscriber-2 and I have received a new book: Book(A book title,List(Author, Another author))
  40.  
  41. system.eventStream.unsubscribe(subscriber2, classOf[Book])
  42.  
  43. bookPublisher ! Book(title = "Another book title", authors = List("Another author"))
  44. // Yeah! Publishing a new book: Book(Another book title,List(Another author))
  45. // My name is subscriber-1 and I have received a new book: Book(Another book title,List(Another author))
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement