Skip to content

Instantly share code, notes, and snippets.

@djspiewak
Last active October 4, 2019 20:28
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 djspiewak/38cc733330564e0757a43115a0e8c0bb to your computer and use it in GitHub Desktop.
Save djspiewak/38cc733330564e0757a43115a0e8c0bb to your computer and use it in GitHub Desktop.
def interruptable[F[_]: Concurrent: ContextShift](thunk: => A): F[A] = {
val fa: F[A] = Concurrent[F] cancelable { cb =>
val done = new AtomicBoolean(false)
val t = new Thread { () =>
try {
val result = thunk
done.set(true)
cb(Right(result))
} catch {
case NonFatal(e) =>
done.set(true)
cb(Left(e))
case t: Throwable =>
done.set(true)
throw t
}
}
t.setDaemon(true)
t.setName("interruptable-thingy-todo")
t.start()
Sync[F] delay {
while (!done.get()) {
t.interrupt()
}
}
}
fa.guarantee(ContextShift[F].shift)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment