当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何将Future[Vector[UserLocation]]转换为Future[Vector[User]]》经验,为你挑选了1个好方法。

我有一个方法,我想返回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> Michael Zaja..:

如果你mapFuture[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
}

推荐阅读
无名有名我无名_593
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有