2017-11-21 28 views
2

멋진 모나드 방식으로 비동기 프로세스를 작성하는 방법에 어려움을 겪고 있습니다. 프로세스의 각 단계가 실패하여 Future[Either[String, T]]을 검색 할 수 있습니다.이해를 돕기 위해 Future and Either

def firstStep(input: Int): Future[Either[String, Long]] = ??? 
def secondStep(input: Long): Future[Either[String, String]] = ??? 
def thirdStep(input: String): Future[Either[String, Double]] = ??? 

내가이

def process(input: Int): Future[Either[String Double]] = { 
    for{ 
     res1 <- firstStep(input) 
     res2 <- secondStep(res1) 
     res3 <- thirdStep(res2) 
    } yield res3 
} 

처럼을 구성하려는 이러한 기능을 감안할 그러나 각 부분 결과가 Either[String, T] 때문에이 작동하지 않습니다, 그리고 내가 필요한 것은 T 자체 (또는 실행을 중지하고 Left을 반환하십시오).

좋은 모나 딕 방식으로 (for-comprehensions를 사용하여) 어떻게이 함수를 작성할 수 있습니까?

답변

3

EitherT 모나드 변압기 중 하나 (말장난 의도) 고양이 또는 scalaz에서 도움이 될 수 있습니다

import cats._ 
import cats.implicits._ 
import cats.EitherT 

def process(input: Int): Future[Either[String, Double]] = { 
    val res = for { 
     res1 <- EitherT(firstStep(input)) 
     res2 <- EitherT(secondStep(res1)) 
     res3 <- EitherT(thirdStep(res2)) 
    } yield res3 
    res.value 
} 
+0

덕분에 하나 개의 질문입니다 선물을 통해 차단의 종류를 수행하는이 솔루션? – Mikel

+1

@Mikel 아니요.이 호출은 모두'EitherT'에서'flatMap'과'map' 호출입니다. –