ksp0422
ksp0422

Reputation: 349

How do I compose multiple monads? IO / Future and maybe with even State and Option

I'm trying to compose monads in Scala doing some requests to server. here is the code snippet that I'm using. I try not to use flatmap as possible only using for comprehension as well. any ideas? I know using Monad Transformers, but I don't know how to compose multiple monads. can anyone help me out?

for {
  session <- getSession(ticker) //IO[Future[Response]]
  crumbF = session.flatMap(response => Future(parseCrumb(response.body)))
  cookiesF = session.flatMap(response => Future(response.cookies))
  crumb = Await.result(crumbF, 5 seconds) // Future[String]
  cookies = Await.result(cookiesF, 5 seconds) //Future[Seq[Cookies]]
  data <- getData(ticker, startDate, endDate, interval, crumb, cookies.head) // IO[Future[Response]]
  stocksF = data.flatMap { response =>
    import DefaultBodyReadables._
    Future {
      StockDf.mapDataToDf(response.body)
    }
  }
} yield stocksF

Upvotes: 0

Views: 232

Answers (1)

Terry Dactyl
Terry Dactyl

Reputation: 1868

So a few things.

If you launch futures inside a for comprehension then they will run in sequence rather than in parallel - if this is your intention then fine. If not then instantiate them outside the for comprehension.

You cannot mix monadic contexts inside a for comprehension.

// Yes
for {
  a <- Some(5)
  b <- Some(10)
} yield 5 * 10

// No
for {
  a <- Some(5)
  b <- Future(10)
} yield 5 * 10

Upvotes: 3

Related Questions