Skip to content

Instantly share code, notes, and snippets.

@roman
Last active December 17, 2015 08:09
Show Gist options
  • Save roman/5578294 to your computer and use it in GitHub Desktop.
Save roman/5578294 to your computer and use it in GitHub Desktop.
Implementation of sourceTimer in Conduit 0.5.x
import Control.Concurrent (forkIO,
killThread,
threadDelay)
import Control.Monad (void)
import Control.Concurrent.STM (atomically)
import Control.Monad.Trans (MonadIO(..))
import Control.Concurrent.STM.TChan (TChan, newTChan, writeTChan, readTChan)
import Control.Monad.Trans.Resource (MonadResource, allocate)
import Data.Conduit (Source, awaitE)
import Data.Conduit.Internal (Pipe(..))
sourceTChan :: MonadIO m => TChan a -> Source m a
sourceTChan ch = src
where
src = PipeM pull
pull = do
a <- liftIO $ atomically $ readTChan ch
return $ HaveOutput src (return ()) a
sourceTimer :: MonadResource m => Int -> Source m Int
sourceTimer micro = do
chan <- liftIO . atomically $ newTChan
void $ allocate (forkIO $ timerThread 0 chan) (killThread)
sourceTChan chan
where
timerThread i chan = do
threadDelay micro
liftIO . atomically $ writeTChan chan i
timerThread (i + 1) chan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment