Last active
December 17, 2015 08:09
-
-
Save roman/5578294 to your computer and use it in GitHub Desktop.
Implementation of sourceTimer in Conduit 0.5.x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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