Scala - how to use foreach loop in for comprehensi

2020-05-06 11:11发布

I have a simple code:

 override def createContributorsList(url: String, params: String): F[List[Contributor]] = getContributorsFromClient(url, params).fold[List[Contributor]](_ => List(), res => res)

 override def createReposList(organization: String, params: String): F[List[GitRepository]] = getReposFromClient(organization, params).fold[List[GitRepository]](_ => List(), res => res)

This code return list of repositories from github and list of contributions. But now I need to call createContributorsList for every repository I found by createReposList. I have done a for comprehension block:

val stats = new StatisticsRepository[IO](new GitHttpClient[IO])
val res = for {
    repos <- stats.createReposList("github", "")
  } yield repos

It works fine, it found repositories for given organization (github). So I tried do it like this:

val res = for {
    repos <- stats.createReposList("github", "")
    list = repos.foreach(repo => stats.createContributorsList(repo.contributors_url, ""))
  } yield (repos, list)

But list is always empty. I don't know how I could do this without for comprehension, because I operate here on Monads like IO. How I should create a code to loop over every repo from repos and call stats.createContributorsList on everyone?

1条回答
Bombasti
2楼-- · 2020-05-06 11:52

Try flatTraverse

import cats.syntax.flatMap._
import cats.syntax.functor._
import cats.syntax.traverse._
import cats.instances.list._

val res: F[(List[GitRepository], List[Contributor])] = for {
  repos <- stats.createReposList("github", "")
  list <- repos.flatTraverse(repo => stats.createContributorsList(repo.contributors_url, ""))
} yield (repos, list)

foreach return Unit so that's not what you need.

查看更多
登录 后发表回答