{-# LANGUAGE FlexibleContexts #-}

module Network.AMQP.Worker.Poll where

import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Loops (untilJust)

-- | Keep trying action every N microseconds until it returns Just a
poll :: (MonadIO m) => Int -> m (Maybe a) -> m a
poll :: forall (m :: * -> *) a. MonadIO m => Int -> m (Maybe a) -> m a
poll Int
us m (Maybe a)
action = forall (m :: * -> *) a. Monad m => m (Maybe a) -> m a
untilJust forall a b. (a -> b) -> a -> b
$ do
    Maybe a
ma <- m (Maybe a)
action
    case Maybe a
ma of
        Just a
a -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a
Just a
a
        Maybe a
Nothing -> do
            forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ Int -> IO ()
threadDelay Int
us
            forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing