我有一个方法,我想返回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]]?
如果你map
的Future[Vector[UserLocation]]
,你可以很容易地生成Vector[Future[User]]
内,从包含的Vector[UserLocation]
:
userLocations.map(location => userService.getById(location.userId))
您可以使用Future.sequence
将其反转Vector[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
为a 来修复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 }