Skip to content

Instantly share code, notes, and snippets.

@gvolpe
Last active June 12, 2018 13:33
Show Gist options
  • Save gvolpe/ab764d2fb5d9aa5cd2b3823122d2510e to your computer and use it in GitHub Desktop.
Save gvolpe/ab764d2fb5d9aa5cd2b3823122d2510e to your computer and use it in GitHub Desktop.
Java's CompletionStage to Cats Effect F[_]: Async / IO
import java.util.concurrent.CompletionStage
import cats.effect.Async
import cats.syntax.flatMap._
case object EmptyValue extends Throwable
def to[F[_], A](fa: F[CompletionStage[A]])(implicit F: Async[F]): F[A] = {
fa.flatMap { f =>
F.async[A] { cb =>
f.handle[Unit] { (value: A, t: Throwable) =>
if (t != null) cb(Left(t))
else if (value != null) cb(Right(value))
else cb(Left(EmptyValue))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment