Last active
October 4, 2019 20:28
-
-
Save djspiewak/38cc733330564e0757a43115a0e8c0bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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