I have a list of tasks in a for-comprehension:
def main = {
List("en", "es", "de").foreach(c => execAll(c))
}
def execAll(country: String): Future[Unit] = {
for {
_ <- repo.exec1(country)
_ <- repo.exec2(country)
_ <- repo.exec3(country)
_ <- repo.exec4(country)
_ <- repo.exec5(country)
} yield ()
}
The problem now is because I need to execute functions exec4
and exec5
only for "en" and "es" countries.
I tried to add the functions in a list of futures by condition (if country == "en"
don't add it)
val all = for {
_ <- repo.exec1(country)
_ <- repo.exec2(country)
_ <- repo.exec3(country)
} yield ()
val enOrEsOnly = for {
_ <- repo.exec4(country)
_ <- repo.exec5(country)
} yield ()
country match {
case "de" => all
case other => all enOrEsOnly // invalid code
}
Can find a solution using for-comprehension
here? Or can just use a list of futures here? I don't need their results. thanks
Or I can just use an if
to solve it:
if (country != "de") {
repo.exec4(country)
repo.exec5(country)
}
CodePudding user response:
What about replace execAll
by:
def execAll(country: String): Future[Unit] = {
for {
_ <- repo.exec1(country)
_ <- repo.exec2(country)
_ <- repo.exec3(country)
if country != "de"
_ <- repo.exec4(country)
_ <- repo.exec5(country)
} yield ()
}
CodePudding user response:
I would rather add an extra layer over repo
that has the validations, that way your code will be the same, and in that extra layer you would do something like this:
final class Domain(repo: Repository) {
def exec4(country: String): Future[Unit] =
country match {
case "en" | "es" => repo.exec4(country)
case _ => Future.unit
}
}