pekko/akka-core/src/main/scala/routing/Patterns.scala

53 lines
1.9 KiB
Scala
Raw Normal View History

/**
* Copyright (C) 2009-2010 Scalable Solutions AB <http://scalablesolutions.se>
*/
package se.scalablesolutions.akka.patterns
2010-02-13 21:45:35 +01:00
2010-05-06 08:13:12 +02:00
import se.scalablesolutions.akka.actor.{Actor, ActorRef}
import se.scalablesolutions.akka.actor.Actor._
2010-02-13 21:45:35 +01:00
object Patterns {
type PF[A, B] = PartialFunction[A, B]
2010-02-13 21:45:35 +01:00
2010-05-06 22:27:59 +02:00
/** Creates a new PartialFunction whose isDefinedAt is a combination
2010-02-13 21:45:35 +01:00
* of the two parameters, and whose apply is first to call filter.apply and then filtered.apply
*/
def filter[A, B](filter: PF[A, Unit], filtered: PF[A, B]): PF[A, B] = {
case a: A if filtered.isDefinedAt(a) && filter.isDefinedAt(a) =>
2010-02-13 21:45:35 +01:00
filter(a)
filtered(a)
}
2010-05-06 22:27:59 +02:00
/** Interceptor is a filter(x,y) where x.isDefinedAt is considered to be always true
2010-02-13 21:45:35 +01:00
*/
2010-03-17 17:48:46 +01:00
def intercept[A, B](interceptor: (A) => Unit, interceptee: PF[A, B]): PF[A, B] =
filter({case a if a.isInstanceOf[A] => interceptor(a)}, interceptee)
2010-05-06 22:27:59 +02:00
/** Creates a LoadBalancer from the thunk-supplied InfiniteIterator
*/
def loadBalancerActor(actors: => InfiniteIterator[ActorRef]): ActorRef =
2010-05-08 15:59:11 +02:00
actorOf(new Actor with LoadBalancer {
2010-05-05 13:26:31 +02:00
val seq = actors
}).start
2010-05-05 13:26:31 +02:00
2010-05-06 22:27:59 +02:00
/** Creates a Dispatcher given a routing and a message-transforming function
*/
def dispatcherActor(routing: PF[Any, ActorRef], msgTransformer: (Any) => Any): ActorRef =
2010-05-08 15:59:11 +02:00
actorOf(new Actor with Dispatcher {
2010-05-05 13:26:31 +02:00
override def transform(msg: Any) = msgTransformer(msg)
def routes = routing
}).start
2010-05-06 22:27:59 +02:00
/** Creates a Dispatcher given a routing
*/
2010-05-08 15:59:11 +02:00
def dispatcherActor(routing: PF[Any, ActorRef]): ActorRef = actorOf(new Actor with Dispatcher {
def routes = routing
}).start
2010-02-13 21:45:35 +01:00
2010-05-06 22:27:59 +02:00
/** Creates an actor that pipes all incoming messages to
* both another actor and through the supplied function
*/
2010-05-06 08:13:12 +02:00
def loggerActor(actorToLog: ActorRef, logger: (Any) => Unit): ActorRef =
2010-03-17 17:48:46 +01:00
dispatcherActor({case _ => actorToLog}, logger)
2010-04-24 14:56:50 +02:00
}