Skip to content

Instantly share code, notes, and snippets.

@rkuhn
Last active December 24, 2018 17:27
Show Gist options
  • Save rkuhn/5116004 to your computer and use it in GitHub Desktop.
Save rkuhn/5116004 to your computer and use it in GitHub Desktop.
Sample code for the blog post about Typed Channels in Akka
/**
* Copyright (C) 2013 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.channels
import akka.actor.{ Actor, ActorSystem }
import akka.channels._
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.Await
import java.lang.{ Double ⇒ JDouble }
class Squarer extends Actor
with Channels[TNil, (JDouble, Double) :+: TNil] {
channel[JDouble] {
case (x, send) ⇒
send <-!- x * x
}
}
class StringToDouble(target: ⇒ Actor with Channels[TNil, (JDouble, Double) :+: TNil])
extends Actor with Channels[TNil, (String, String) :+: TNil] {
import java.lang.Double.valueOf
// needed for the Future.map below
import context.dispatcher
// needed for the -?-> below
implicit val timeout = Timeout(5.seconds)
lazy val targetRef = createChild(target, "calculator")
channel[String] {
case (str, sender) ⇒
valueOf(str) -?-> targetRef -*-> (_.map(_.toString)) -!-> sender
}
}
object Demo extends App {
implicit val timeout = Timeout(1.second)
val system = ActorSystem("ChannelSample")
import system.dispatcher
val handler = ChannelExt(system).actorOf(new StringToDouble(new Squarer), "handler")
def printLine(): Future[Unit] = Future(readLine) flatMap {
case null | "exit" => Future.successful(())
case line => line -?-> handler flatMap { r => println(r); printLine() }
}
printLine() onComplete (_ ⇒ system.shutdown())
}
object Demo extends App {
implicit val timeout = Timeout(1.second)
val system = ActorSystem("ChannelSample")
import system.dispatcher
val handler =
ChannelExt(system).actorOf(new StringToDouble(new Squarer), "handler")
def printLine(): Future[Unit] = Future(readLine) flatMap {
case null | "exit" => Future.successful(())
case line => line -?-> handler flatMap { r => println(r); printLine() }
}
printLine() onComplete (_ ⇒ system.shutdown())
}
class Squarer extends Actor
with Channels[TNil, (JDouble, Double) :+: TNil] {
channel[JDouble] {
case (x, sender) ⇒
sender <-!- x * x
}
}
class StringToDouble(
target: ⇒ Actor with Channels[TNil, (JDouble, Double) :+: TNil]
)
extends Actor with Channels[TNil, (String, String) :+: TNil] {
import java.lang.Double.valueOf
// needed for the Future.map below
import context.dispatcher
// needed for the -?-> below
implicit val timeout = Timeout(5.seconds)
lazy val targetRef = createChild(target, "calculator")
channel[String] {
case (str, sender) ⇒
valueOf(str) -?-> targetRef -*-> (_.map(_.toString)) -!-> sender
}
}
@rkuhn
Copy link
Author

rkuhn commented Mar 8, 2013

thanks!

@viktorklang
Copy link

You're most welcome!

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