
I just wrote this helper:
import Control.Concurrent import Control.Concurrent.STM import Control.Exception.Safe
pollT :: Int -> IO a -> IO (STM (Maybe a), Async b) pollT delay act = do tv <- atomically (newTVar Nothing) as <- async . forever $ do r <- tryAny act case r of Left _ -> pure () Right r' -> atomically (writeTVar tv (Just r')) threadDelay delay pure (readTVar tv, as)
I was sort of surprised not to find something like this in an existing library. 1. Did I miss an existing implementation? 2. Any problems with this one? 3. Any suggestions for a better name? 4. Any thoughts on the general idea? That is, "run an action periodically, updating a TVar with the result". There's a couple of obvious variations that can be built on top of this, like retrying if the TVar is Nothing when reading from it, or writing Nothing to the TVar when the action fails rather than keeping the old value. Maybe passing in the old value to the action?