Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add withAsyncThrow? #161

Open
lazamar opened this issue Nov 5, 2024 · 1 comment
Open

Add withAsyncThrow? #161

lazamar opened this issue Nov 5, 2024 · 1 comment

Comments

@lazamar
Copy link

lazamar commented Nov 5, 2024

I often need to run some important background task which I don't have to wait on and should be cancelled when I'm done.
However, it should interrupt me if it fails.

I've often needed it when writing tests and have been bitten by using withAsync bg (const fg) and having issues with the background task silently failing.

One possible pattern is to remember to always use link in these cases, but link turns synchronous exceptions into asynchronous ones which is a bit weird and not the most ergonomic pattern.

How about having something like the following? Would make link unnecessary for spawning threads you don't need to wait on.

withAsyncThrow :: IO a -> IO b -> IO b
withAsyncThrow left right =
  withAsync left $ \l -> 
  withAsync right $ \r -> do
  e <- waitEither l r
  case e of
    Left _ -> wait r
    Right v -> return v

Might need a better name (withConcurrent?) but others seem to have come across this need in the past too #128

@mitchellwrosen
Copy link

@lazamar I can recommend ki for this use case, though of course async can achieve a similar effect:

Ki.scoped \scope -> do
  void (Ki.fork scope importantBackgroundTask)
  ...

Here, importantBackgroundTask will run in a separate thread, propagate any exception if it fails, and will automatically be cancelled at the end of the ... block if it's still running.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants