Testing out JmonkeyEngine to make a game in Scala with Akka Actors within a pure FP layer
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.5 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package wow.doge.mygame.events
  2. import akka.actor.typed.ActorRef
  3. import akka.actor.typed.Behavior
  4. import akka.actor.typed.scaladsl.Behaviors
  5. import scala.reflect.ClassTag
  6. import akka.event.EventStream
  7. /**
  8. * A (typed) event bus
  9. * Copied (and repurposed) from Akka's EventStream
  10. */
  11. object EventBus {
  12. sealed trait Command[A]
  13. final case class Publish[A, E <: A](
  14. event: E,
  15. publisherName: String
  16. ) extends Command[A]
  17. final case class Subscribe[A, E <: A](subscriber: ActorRef[E])(implicit
  18. classTag: ClassTag[E]
  19. ) extends Command[A] {
  20. def topic: Class[_] = classTag.runtimeClass
  21. }
  22. final case class Unsubscribe[A, E <: A](subscriber: ActorRef[E])
  23. extends Command[A]
  24. def apply[A](): Behavior[EventBus.Command[A]] =
  25. Behaviors.setup { ctx =>
  26. val eventStream = new EventStream(ctx.system.classicSystem)
  27. new EventBus().eventStreamBehavior(eventStream)
  28. }
  29. }
  30. class EventBus[B] {
  31. import akka.actor.typed.scaladsl.adapter._
  32. private def eventStreamBehavior(
  33. eventStream: akka.event.EventStream
  34. ): Behavior[EventBus.Command[B]] =
  35. Behaviors.receiveMessage {
  36. case EventBus.Publish(event, name) =>
  37. eventStream.publish(event)
  38. Behaviors.same
  39. case s @ EventBus.Subscribe(subscriber) =>
  40. eventStream.subscribe(subscriber.toClassic, s.topic)
  41. Behaviors.same
  42. case EventBus.Unsubscribe(subscriber) =>
  43. eventStream.unsubscribe(subscriber.toClassic)
  44. Behaviors.same
  45. }
  46. }