Skip to content

Instantly share code, notes, and snippets.

@DanielaSfregola
Last active August 13, 2022 00:48
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save DanielaSfregola/db67b323563e06dc0b95 to your computer and use it in GitHub Desktop.
Save DanielaSfregola/db67b323563e06dc0b95 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))
}
@tabithablagdon
Copy link

Thanks for the example? Is there an example testSpec for this example too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment