scala/cats2

Future Traverse

wefree 2023. 2. 13. 12:39

https://github.com/typelevel/cats/issues/4176 에서 처럼, cats-2.7 이후 부터는 더 이상 traverse 로 Future 가 동시에 수행되지 않는다.

 

import cats.syntax.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

object TraverseTest {
  def main(args: Array[String]): Unit = {
    def f(n: Int): Future[Unit] = Future {
      Thread.sleep(1000L)
      println(n)
    }

    val list = (1 to 3).toList
    val x = list.traverse(f) // 이렇게 작성하지 말자!! sequential 수행으로 완료에 3초 이상 걸림 
//    val x = list.map(f).sequence  // cats2 lib 을 사용한다면 이렇게 작성하거나
//    val x = Future.traverse(list)(f)  // stdlib 의 Future.traverse 를 사용해야 함
//  혹은 https://github.com/alexklibisz/futil#parallelism 를 이용하도록 하자!!
    Await.result(x, Duration.Inf)
  }
}