Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import akka.actor.{Actor, ActorRef, ActorSystem, Props}
- //Using Akka Actor library model following YouTube functionality: (Scala)
- //
- //There are two types of actors - "Channel" and "User".
- //User can subscribe to a channel and revert the subscription.
- //When a video is uploaded to a channel all of the subscribers are
- //notified about it.
- //
- //A video is identified by its title. Do not store videos on the channel - just notify about them.
- //Videos should be uploaded from the main thread - do not create user-owner.
- //
- //Both types of actors have to print some messages to the console to inform about actions being performed.
- //Define both classes and companion objects, later should define message types and the "props" methods.
- //
- //Present the functionality. Show that it works for multiple channels and users. (10 pts)
- class Channel extends Actor{
- private var subscribers = List[ActorRef]()
- override def receive: Receive = {
- case Channel.NewMovie(title) => {
- println(s"~~Movie created $title")
- subscribers.foreach(f => f ! User.Notification(title)) // make it foreach
- }
- case Channel.Sub(user) => {
- println(s"Sub Received $user")
- subscribers = user :: subscribers
- }
- case Channel.UnSub(user) => {
- subscribers = subscribers.filter(_ != user)
- println(s"UNSUBSCRIBED $user")
- }
- }
- }
- object Channel {
- case class NewMovie(title: String)
- case class Sub(user: ActorRef)
- case class UnSub(user: ActorRef)
- def props: Props = Props[Channel]
- }
- class User(private val id: Int) extends Actor{
- override def receive: Receive = {
- case User.Notification(title) => {
- println(s"User $id received notification: $title")
- }
- }
- }
- object User{
- var id: Int = 0
- case class Notification(title: String)
- def props() =
- {
- id += 1
- Props(classOf[User], id - 1)
- }
- }
- object MainYouTube {
- def main(args: Array[String]): Unit =
- {
- println("start")
- val actSys = ActorSystem()
- val user1: ActorRef = actSys.actorOf(User.props)
- val user2: ActorRef = actSys.actorOf(User.props)
- val user3: ActorRef = actSys.actorOf(User.props)
- val channel: ActorRef = actSys.actorOf(Channel.props)
- channel ! Channel.Sub(user1)
- channel ! Channel.Sub(user2)
- channel ! Channel.NewMovie("Kapitan Bomba odc. 140")
- channel ! Channel.Sub(user3)
- channel ! Channel.NewMovie("Piesek leszek odc. 999")
- channel ! Channel.UnSub(user3)
- channel ! Channel.NewMovie("Laserowy gniew dzidy odc. 12")
- Thread.sleep(5000)
- println("after sleep")
- actSys.terminate()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement