Created
July 19, 2018 13:32
-
-
Save mithrandi/3d6ff453a2c4e1009ced838456e9a68e to your computer and use it in GitHub Desktop.
This file contains 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 | |
import Control.Concurrent.STM | |
import Control.Exception.Safe | |
import Data.Time.Units | |
pollT :: TimeUnit t => t -> IO a -> IO (STM (Maybe a), Async b) | |
pollT delay act = do | |
tv <- newTVarIO Nothing | |
as <- | |
async . forever $ do | |
r <- tryAny act | |
case r of | |
Left e -> print e | |
Right r' -> atomically (writeTVar tv (Just r')) | |
(threadDelay . fromIntegral . toMicroseconds) delay | |
pure (readTVar tv, as) | |
pollTDef :: TimeUnit t => t -> a -> IO a -> IO (STM a, Async b) | |
pollTDef delay def act = do | |
(r, as) <- pollT delay act | |
pure (fromMaybe def <$> r, as) | |
alwaysFromMaybe :: STM (Maybe a) -> STM a | |
alwaysFromMaybe = (maybe retry pure =<<) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment