handlerToIO: use forkIO in Yesod handlers

23 August, 2012Tags: yesod, haskell.

Two days ago in this patch, the handlerToIO function was added to Yesod. Version 1.1.1 which was just released contains this new function.

handlerToIO allows you to GHandler actions inside IO. A neat use case for this is to use forkIO to fork a thread in a response handler and still be able to run database actions with runDB:

postFooR :: Identifier  Handler RepJson
postFooR id = do
    Just (Entity key _) <- runDB $ getBy $ UniqueIdentifier id

    runInnerHandler <- handlerToIO
    liftIO $ forkIO $ runInnerHandler $ do
        result <- liftIO $ actionTakingALongTime
        runDB $ insert $ ResultItem key result
    jsonToRepJson $ String ""