GenEvent

Event Handling Principles

See: Erlang gen_event Behaviour

GenEvent Typeclass

  1. class GenEvent e st | e -> st, st -> e where
  2. handleEvent :: HandleEvent e st

Event Manager Example

  1. module Demo.Event
  2. ( Event(..)
  3. , start
  4. , notify
  5. ) where
  6. import Prelude
  7. import Control.Behaviour.GenEvent
  8. ( class GenEvent
  9. , Init
  10. , initOk
  11. , HandleEvent
  12. , startLinkWith
  13. )
  14. import Control.Behaviour.GenEvent as E
  15. data Event = EventA | EventB
  16. data State = State [Event]
  17. instance GenEvent Event State where
  18. handleEvent = handleEvent
  19. name :: Atom
  20. name = :event
  21. start :: Process Pid
  22. start = startLinkWith name init
  23. notify :: Event -> Process ()
  24. notify = E.notify name
  25. init :: Init State
  26. init = initOk (State [])
  27. handleEvent :: HandleEvent Event State
  28. handleEvent e (State events) = do
  29. println "Event"
  30. return $ State [e|events]

Start a Event Manager process

  1. -- | Start a standalone Event Manager process.
  2. start :: forall e st. GenEvent e st => (Init st) -> Process Pid
  3. startWith :: forall e st. GenEvent e st => Name -> (Init st) -> Process Pid
  4. -- | Start a Event Manager process as part of a supervision tree.
  5. startLink :: forall e st. GenEvent e st => (Init st) -> Process Pid
  6. startLinkWith :: forall e st. GenEvent e st => Name -> (Init st) -> Process Pid

Init callback

  1. data InitResult st
  2. = InitOk st
  3. | InitOkHib st
  4. | InitError ExitReason
  5. -- | Init callback
  6. type Init st = Process (InitResult st)

HandleEvent Callback

  1. -- | HandleEvent callback
  2. type HandleEvent e st = e -> st -> Process st

Client APIs

  1. notify :: forall e. Name -> e -> Process ()
  2. syncNotify :: forall e. Name -> e -> Process ()