Created
September 5, 2016 03:31
-
-
Save fbrubacher/1c52e4de2a7ac72de24c30873f58406a to your computer and use it in GitHub Desktop.
XorT and Future and Either
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
package cats | |
import cats.instances.all._ | |
import cats.data.XorT | |
import scala.concurrent.{Future, ExecutionContext} | |
case class User(val id: Integer, val name: String) | |
class UserRepo { | |
type UserId = Integer | |
object Error | |
case class UserNotFound(userId: Long) extends Error | |
case class ConnectionError(message: String) extends Error | |
def followers(userId: Long)(implicit ec: ExecutionContext): XorT[Future, Error, List[User]] = | |
userId match { | |
case 0L => | |
XorT.right(Future { List(User(1, "Michael")) }) | |
case 1L => | |
XorT.right(Future { List(User(0, "Vito")) }) | |
case x => | |
println("not found") | |
XorT.left(Future.successful { UserNotFound(x) }) | |
} | |
// def isFriends0(u1: UserId, u2: UserId)(implicit ec: ExecutionContext): Future[Either[Error, Boolean]] = | |
// for { | |
// a <- followers(u1) | |
// b <- followers(u2) | |
// } yield for { | |
// x <- a.right | |
// y <- b.right | |
// } yield x.exists(_.id == u2) && y.exists(_.id == u1) | |
def isFriends(u1: Long, u2: Long)(implicit ec: ExecutionContext): XorT[Future, Error, Boolean] = | |
for { | |
a <- followers(u1) | |
b <- followers(u2) | |
} yield a.exists(_.id == u2) && b.exists(_.id == u1) | |
} | |
// def isFriends2(u1: UserId, u2: UserId)(implicit ec: ExecutionContext): Future[Either[Error, Boolean]] = | |
// followers(u2).flatMap { | |
// case Right(a) => | |
// followers(u2).map { | |
// case Right(b) => | |
// Right(a.exists(._id == u2) && b.exists(._id == u2)) | |
// case Left(e) => | |
// Left(e) | |
// } | |
// case Left(e) => Future.successful(e) | |
// } | |
// | |
// } | |
object Test extends App { | |
implicit val ec = scala.concurrent.ExecutionContext.global | |
import scala.concurrent.Await | |
import UserRepo | |
import scala.concurrent.duration._ | |
Await.result(isFriends(0, 3).value, 1.second) | |
Await.result(isFriends(2, 3).value, 1.second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment