Skip to content

Instantly share code, notes, and snippets.

@dgendill
Created March 4, 2017 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgendill/4222efd79e9f8db34ef3dcf25500fbfe to your computer and use it in GitHub Desktop.
Save dgendill/4222efd79e9f8db34ef3dcf25500fbfe to your computer and use it in GitHub Desktop.
How to cancel an Aff

How to cancel an Aff

The PureScript purescript-aff library provides launchAff, runAff, and forkAff which all return a Canceler that can be passed into cancel to attempt cancelation of the asynchronous process.

module Main where
import Prelude
import Data.Either (either)
import Control.Monad.Aff (Aff, attempt, cancel, forkAff, later', launchAff)
import Control.Monad.Aff.Console (CONSOLE, log, logShow)
import Control.Monad.Eff.Exception (error)
getUpdate :: forall e. Aff (console :: CONSOLE | e) String
getUpdate = do
later' 10000 do
pure "Server update"
main = void $ launchAff $ do
-- Fork the async showFeedback function and
-- store its canceler. This function will
-- run forever until it's canceled
feedbackProcess <- forkAff $ later' 2000 showFeedback
-- Aff e (Either Error a)
update <- attempt $ getUpdate
-- Attempt to cancel the feedback process, we
-- have a response from the server. Cancel will return
-- true or false indicating if the cancelation was successful.
-- I'm not sure what the purpose of the second error argument is -
-- I'm assuming that's a way to say why the cancelation failed?
cs <- cancel feedbackProcess (error "Could not cancel showFeedback process.")
case cs of
true -> log "feedbackProcess canceled"
false -> log "feedbackProcess could not be canceled."
log "(delay)"
later' 5000 do
either logShow log update
where
showFeedback = do
log "Fetching update, please wait..."
later' 2000 showFeedback
Fetching update, please wait...
Fetching update, please wait...
Fetching update, please wait...
Fetching update, please wait...
feedbackProcess canceled
(delay)
Server update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment