如何将Future [Vector [UserLocation]]转换为Future [Vector [User]]

时间:2015-12-15 04:00:52

标签: scala future

我有一个方法,我想返回Future[Vector[user]]

方法userLocationService.getUserLocationsInList将返回Future[Vector[UserLocation]]

其中UserLocation类似于:

case class UserLocation(id: Int, locationId: Int, userId: Int)


def getUsersInLocation(locationIdList: Set[Int]): Future[Vector[User]] = {

   userLocationService.getUserLocationsInList(locationIdList).map{
      userLocations =>
          // ????????????
   }

}

我有一个基于UserId返回单个用户的方法,如:

userService.getById(userId: Int): Future[User]

如何根据上述内容构建Future [Vector [User]]?

1 个答案:

答案 0 :(得分:7)

如果您map Future[Vector[UserLocation]],则可以从包含的Vector[Future[User]]内轻松生成Vector[UserLocation]

userLocations.map(location => userService.getById(location.userId))

您可以使用Future.sequenceVector[Future[User]]转换为Future[Vector[User]]

Future.sequence(userLocations.map(location => userService.getById(location.userId)))

或使用Future.traverse

Future.traverse(userLocations) { location => userService.getById(location.userId) }

这将为您留下Future[Future[Vector[User]]],可以通过将map更改为flatMap来解决此问题。把它们放在一起:

def getUsersInLocation(locationIdList: Set[Int]): Future[Vector[User]] = {
  userLocationService.getUserLocationsInList(locationIdList).flatMap { locations =>
    Future.traverse(locations) { location =>
      userService.getById(location.userId)
    }
  }
}

或者为了理解:

def getUsersInLocation(locationIdList: Set[Int]): Future[Vector[User]] = {
  for {
    locations <- userLocationService.getUserLocationsInList(locationIdList)
    users <- Future.traverse(locations) { location =>
      userService.getById(location.userId)
    }
  } yield users
}