Alb*_*urg 2 scala future playframework-2.0
开始玩Scala期货,我陷入了依赖期货的困境.
我们来举个例子.我搜索地点并得到一个Future[Seq[Place]].对于每个地方,我搜索最近的地铁站(服务重新出发Future[List[Station]]).
我会写这个:
Place.get()
.map { places =>
places.map { place =>
Station.closestFrom(place).map { stations =>
SearchResult(place, stations)
}
}
}
Run Code Online (Sandbox Code Playgroud)
那件事会让我得到Future[Seq[Future[SearchResult]]]......这不是我所期待的.
我错过了Future[Seq[SearchResult]]什么?
谢谢大家,
阿尔班
您Future在解决方案中缺少两个概念:flatMap和Future.sequence
解释每个:
flatMap就像是,map除了给它一个函数,future.map(A => B)你给它一个函数future.flatMap(A => Future[B]).这样你就可以将期货连在一起了.
Future.sequence 是一个帮助函数,它将期货列表与列表的未来结合起来: Seq[Future[A]] => Future[Seq[A]]
使用FutureAPI的这两个功能,我们可以将您的答案更改为:
Place.get().flatMap { places =>
Future.sequence(places.map { place =>
Station.closestFrom(place).map { stations =>
SearchResult(place, stations)
}
})
}
Run Code Online (Sandbox Code Playgroud)