Last active
December 5, 2017 07:55
-
-
Save Tvaroh/522169efa3eecd4eba7c92e164e9c0f9 to your computer and use it in GitHub Desktop.
TODO
This file contains hidden or 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
import cats.{Monad, StackSafeMonad} | |
import cats.effect.{IO, LiftIO} | |
trait Session { | |
def close(): Unit | |
} | |
case class SessionContext[T](exec: Session => IO[T]) { | |
def runSession(newSession: () => Session): IO[T] = { | |
val session = newSession() | |
exec(session).map { t => | |
session.close() | |
t | |
} | |
} | |
} | |
object SessionContext { | |
implicit val instance: Monad[SessionContext] with LiftIO[SessionContext] = | |
new StackSafeMonad[SessionContext] with LiftIO[SessionContext] { | |
override def pure[A](a: A): SessionContext[A] = | |
SessionContext(Function.const(IO.pure(a))) | |
override def flatMap[A, B](fa: SessionContext[A]) | |
(f: A => SessionContext[B]): SessionContext[B] = | |
SessionContext(session => fa.exec(session).flatMap(a => f(a).exec(session))) | |
override def liftIO[A](io: IO[A]): SessionContext[A] = | |
SessionContext(Function.const(io)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment