Last active
June 29, 2017 09:32
-
-
Save pbassiner/bb820da4a662103e3a9e3b595d0e4ea5 to your computer and use it in GitHub Desktop.
From List[Either[A, B]] to Either[A, List[B]]
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
import scala.language.postfixOps | |
import scala.concurrent.ExecutionContext | |
import scala.concurrent.Future | |
import cats.data.EitherT | |
import cats.instances.list._ | |
import cats.instances.future._ | |
import cats.syntax.traverse._ | |
implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global | |
def getCommitsWithAuthor(): Future[Either[Error, List[CommitAndAuthor]]] = | |
(for { | |
commits <- EitherT(getCommits()) | |
result <- commits.map { commit => | |
EitherT(getAuthor(commit.id)) map { author => CommitAndAuthor(commit, author) } | |
}.sequenceU | |
} yield result).value | |
final case class Commit(id: String) | |
final case class Author(id: String) | |
final case class CommitAndAuthor(commit: Commit, author: Author) | |
sealed trait Error | |
def getCommits(): Future[Either[Error, List[Commit]]] = | |
Future.successful( | |
Right( | |
List( | |
Commit("abcdef"), | |
Commit("ghijk") | |
) | |
) | |
) | |
def getAuthor(commitId: String): Future[Either[Error, Author]] = | |
Future.successful( | |
Right( | |
Author("me") | |
) | |
) | |
import scala.concurrent.Await | |
import scala.concurrent.duration._ | |
println(Await.result(getCommitsWithAuthor(), 10000 millis)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment