LoginSignup
0

More than 3 years have passed since last update.

EitherTを使ってfor内包表記で並列に動かすやり方

Posted at

これは並列処理されない

qiita.scala
type ProcessR[T] = EitherT[Future, Errors, T]

for{
  a <- ProcessR(~~~)
  b <- ProcessR(~~~)
} yield (a, b)

flatMapは前のbindが完了してから次の処理に進むため

これは並列処理される

qiita.scala
val aPr = ProcessR(~~~)
val bPr = ProcessR(~~~)
for{
  a <- aPr
  b <- bPr
} yield (a, b)

valで定義した瞬間にFutureが走るため

for内包表記が使いたいが、直列では動かしたくない!
って時は自分で拡張しよう

qiita.scala
  def join[A, B](
    aF: ProcessR[A],
    bF: ProcessR[B]
  )(implicit ec: ExecutionContext): ProcessR[(A, B)] =
    for {
      a <- aF
      b <- bF
    } yield (a, b)

このようにProcessRのコンパニオンか何かによく使う関数を定義しておけば

val aF: ProcessR[A],
val bF: ProcessR[B]
と引数でval宣言しているのと同義なので、これは

qiita.scala
for {
a <- join(ProcessR(~~~), ProcessR(~~~))
} yield (a._1, a._2)

とfor内包表記で書きながらも並列に処理ができる

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0