繁体   English   中英

Scala 期货使用 Future.sequence 但返回元组有问题

[英]Scala futures using Future.sequence but having issues with returning a tuple

当我在下面使用Future.sequence时,我在尝试返回元组时遇到了一些麻烦:

type UserId = Int
  type GameId = Int
  type Score = Double

  case class Game(id: GameId)

  def findGame(id: GameId): Future[Game] = ???
  def findUserGames(id: UserId): Future[Seq[(GameId, Score)]] = ???

  def findGames(id: UserId): Future[Seq[(Game, Score)]] = {
    val userGames = findUserGames(id)

    // ******* I am stuck here
    val games: Future[Seq[Game]] = userGames.flatMap(x => Future.sequence(x.map(y => findGame(y._1))))    
  }

当 Future.sequence 调用只是返回给我一个Seq[Game]时,我如何返回一个(Game, Score)的元组?

另外,如果我们没有Future.sequence ,我们如何能够模仿它的作用? 即将List[Future[Game]]转换成Future[List[Game]]

你可以试试这个:

def findGames(id: UserId): Future[Seq[(Game, Score)]] = {
  findUserGames(id).flatMap(gameIdToScoreSeq =>
    Future.traverse(gameIdToScoreSeq)(gameIdToScore =>
      findGame(gameIdToScore._1).map((_, gameIdToScore._2))
    )
  )
}

只需跟踪名称是什么,作为oneliner,您就可以做到

def findGames(id: UserId)(implicit ec: ExecutionContext): Future[Seq[(Game, Score)]] =
  findUserGames(id).flatMap(games =>
    Future.sequence(games.map { case (gameid, score) =>
      findGame(gameid).map(game => game -> score)
    })
  )

你只需要一个 map:

val games: Future[Seq[(Game, Score)]] = userGames.flatMap(x => Future.sequence(x.map(y => findGame(y._1).map(z => (z, y._2)))))

正如你所看到的,它变得有点复杂。 您可以通过使用 for-comprehensions 和模式匹配使您的代码更具可读性(可以说是):

val games2: Future[Seq[(Game, Score)]] = for {
  games <- userGames
  result <- Future.sequence(games.map {
    case (gameId, score) => 
      for {
        game <- findGame(gameId)
      } yield (game, score)
  })
} yield result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM