alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Akka/Scala example source code file (Listeners.scala)

This example Akka source code file (Listeners.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Akka and Scala source code examples by using tags.

All credit for the original source code belongs to akka.io; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Akka tags/keywords

actor, actorref, akka, any, deafen, listen, listenermessage, listeners, route, router, routing, set, unit, withlisteners

The Listeners.scala Akka example source code

/**
 * Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
 */

package akka.routing

import akka.actor.{ Actor, ActorRef }
import java.util.{ Set, TreeSet }

sealed trait ListenerMessage
final case class Listen(listener: ActorRef) extends ListenerMessage
final case class Deafen(listener: ActorRef) extends ListenerMessage
final case class WithListeners(f: (ActorRef) ⇒ Unit) extends ListenerMessage

/**
 * Listeners is a generic trait to implement listening capability on an Actor.
 * <p/>
 * Use the <code>gossip(msg)</code> method to have it sent to the listeners.
 * <p/>
 * Send <code>Listen(self)</code> to start listening.
 * <p/>
 * Send <code>Deafen(self)</code> to stop listening.
 * <p/>
 * Send <code>WithListeners(fun)</code> to traverse the current listeners.
 */
trait Listeners { self: Actor ⇒
  protected val listeners: Set[ActorRef] = new TreeSet[ActorRef]

  /**
   * Chain this into the receive function.
   *
   * {{{ def receive = listenerManagement orElse … }}}
   */
  protected def listenerManagement: Actor.Receive = {
    case Listen(l) ⇒ listeners add l
    case Deafen(l) ⇒ listeners remove l
    case WithListeners(f) ⇒
      val i = listeners.iterator
      while (i.hasNext) f(i.next)
  }

  /**
   * Sends the supplied message to all current listeners using the provided sender() as sender.
   *
   * @param msg
   * @param sender
   */
  protected def gossip(msg: Any)(implicit sender: ActorRef = Actor.noSender): Unit = {
    val i = listeners.iterator
    while (i.hasNext) i.next ! msg
  }
}

Other Akka source code examples

Here is a short list of links related to this Akka Listeners.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.