Skip to content

Instantly share code, notes, and snippets.

@seanhess
Created February 2, 2016 21:22
Show Gist options
  • Save seanhess/5a31c4aed4641e693df3 to your computer and use it in GitHub Desktop.
Save seanhess/5a31c4aed4641e693df3 to your computer and use it in GitHub Desktop.
Why Haskell helps with reusability
-- First, I made it application specific
attemptConnect :: Int -> TWInfo -> Manager -> APIRequest apiName responseType -> ResourceT IO (ResumableSource (ResourceT IO) StreamingAPI)
attemptConnect delay twInfo mgr = do
ms <- streamShowStatus twInfo mgr (statusesFilter accountName [accountID])
case ms of
Just s -> return s
Nothing -> do
liftIO $ putStrLn ("FAILED, delaying for " <> show delay <> "s")
liftIO $ threadDelay (delay * 1000 * 1000)
attemptConnect (delay*2) twInfo mgr
-- retries with a delay, can be used for any monadic action that returns (Maybe a)
-- will keep trying until it gets a value
-- EXAMPLE:
-- retryWithDelay 60 (*2) $ streamShowStatus twInfo mgr (statusFilter accountName [accountID])
retryWithDelay :: MonadIO m => Int -> (Int -> Int) -> m (Maybe a) -> m a
retryWithDelay delay grow action = do
ma <- action
case ma of
Just a -> return a
Nothing -> do
liftIO $ putStrLn ("FAILED, delaying for " <> show delay <> "s")
liftIO $ threadDelay (delay * 1000 * 1000)
retryWithDelay (grow delay) grow action
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment