pituicat/src/Affection/MessageBus/Util.hs
2017-11-27 23:30:11 +01:00

32 lines
1.1 KiB
Haskell

module Affection.MessageBus.Util where
import Affection.MessageBus.Class
import Affection.MessageBus.Message
import Affection.Types
import Control.Concurrent.STM as STM
-- | Build a new broadcast channel
newBroadcastChannel :: (Message msg) => IO (Channel msg)
newBroadcastChannel = atomically $ Channel <$> newBroadcastTChan
-- | Duplicate a broadcast channel, so it can be accessed by subsystems
dupChannel :: (Message msg)
=> Channel msg -- ^ Original 'Channel'
-> IO (Channel msg) -- ^ 'Channel' duplicate
dupChannel (Channel c) = atomically $ Channel <$> dupTChan c
-- | Try to read a 'Channel' wihtout deleting the message. Returns 'Nothing' on
-- an empty 'Channel'
tryPeekChannel :: (Message msg)
=> Channel msg -- ^ Channel to read from
-> IO (Maybe msg) -- ^ Resulting message (or not)
tryPeekChannel (Channel c) = atomically $ tryPeekTChan c
-- | Write a message to a 'Channel' and thus broadcast it to all connected
-- subsystems
writeChannel :: (Message msg)
=> Channel msg -- ^ 'Channel' to write to
-> msg -- ^ The Message to emit
-> IO ()
writeChannel (Channel c) m = atomically $ writeTChan c m