Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save batakpout/38d4f2183de5405cdf44a91b45fca483 to your computer and use it in GitHub Desktop.
Save batakpout/38d4f2183de5405cdf44a91b45fca483 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/
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