ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Future[Try[A]] <=> Future[A] 상호간 변환하기
    scala/basic 2023. 1. 16. 12:58

    Future[Try[A]] <=> Future[A]  변환

     

    Future[Try[A]] => Future[A]

    import scala.concurrent.ExecutionContext.Implicits.global
    import scala.concurrent.Future
    import scala.util.{Success, Try}
    
    object FutureTryTest {
      def main(args: Array[String]): Unit = {
        val futureTry: Future[Try[Int]] = Future(Success(1))
        
        // https://github.com/monix/monix/blob/series/3.x/monix-execution/shared/src/main/scala/monix/execution/FutureUtils.scala#L119-L120
        val future1: Future[Int] = futureTry.map(_.get)
        
        // https://github.com/scala-hamsters/hamsters/blob/3.1.0/shared/src/main/scala/io/github/hamsters/FutureOps.scala#L26-L28
        val future2: Future[Int] = futureTry.flatMap(Future.fromTry)
      }
    }

    그러나 이렇게 한다고 해서 Try[A] 의 evaluation 이 async 처리되는 것은 아니다. blocking 으로 똑 같이 처리되고, 다만 Future 로 감싸주는 역할만 할 뿐!

     

    Future[A] => Future[Try[A]]

    import scala.concurrent.ExecutionContext.Implicits.global
    import scala.concurrent.Future
    import scala.util.{Success, Try}
    
    object FutureTryTest2 {
      def main(args: Array[String]): Unit = {
        val future: Future[Int] = Future.failed[Int](new Exception("some error"))
    
        val futureTry: Future[Try[Int]] = future.map(Success(_)).recover(Failure(_))
        
        // https://github.com/monix/monix/blob/series/3.x/monix-execution/shared/src/main/scala/monix/execution/FutureUtils.scala#L96-L98
        val futureTry: Future[Try[Int]] = future.transform(t => Success(t))
        println(futureTry) // Future(Success(Failure(java.lang.Exception: some error)))
      }
    }

    'scala > basic' 카테고리의 다른 글

    Blocking Future  (0) 2023.02.13
    Environment, Property variable 읽기  (0) 2023.02.03
    Error Modeling (with Exception)  (0) 2023.01.16
    Scala Using  (0) 2022.12.19
    F-Bound  (0) 2022.11.12

    댓글

Designed by Tistory.