0

我有一个返回字符串的 Akka HTTP 服务,如下所示:

val route1: Route = {
    path("hello") {
      get{
        complete{
          println("Inside r1")
          "You just accessed hello"
        }
      }
   }
}

我试图了解 map 和 flatMap 之间的区别

例如,下面的代码给了我预期的结果:

val future1: Future[String] = 
  Http()
   .singleRequest(
      HttpRequest(method = HttpMethods.GET,
                  uri = "http://localhost:8187/hello"))
   .flatMap(testFlatFunc)

def testFlatFunc(x: HttpResponse): Future[String] = {
  Unmarshal(x).to[String]
}

但是,如果我尝试用地图替换它,如下所示,我得到的输出为FulfilledFuture(You just accessed hello)

val future1: Future[String] = Http()
    .singleRequest(
      HttpRequest(method = HttpMethods.GET,
                  uri = "http://localhost:8187/hello"))
    .map(testFunc)

def testFunc(x: HttpResponse): String={
  Unmarshal(x).to[String].toString
}

为什么我的 map() 没有按预期工作?

4

2 回答 2

1

mapflatMap区别:

flatMap将折叠一层嵌套结构(它调用fallten),例如:List(List(1), List(2)).flatMap(i => i)将是:List(1, 2)

所以你的代码,testFlatFunc返回testFunc 类型Future[String],函数返回类型也是map,但是会扁平化嵌套结构,所以:会扁平化为。和函数不会这样做,所以:flatMapFuture[T]flatMapFuture[Future[String]]Future[String]map

 val future1:Future[String] = Http()
    .singleRequest(
      HttpRequest(method = HttpMethods.GET,
                  uri = "http://localhost:8187/hello")).map(testFunc)

返回类型应该是:

 val future1:Future[Future[String]] = Http()
    .singleRequest(
      HttpRequest(method = HttpMethods.GET,
                  uri = "http://localhost:8187/hello")).map(testFunc)
于 2017-02-20T05:51:52.037 回答
1

这是关于你在做什么testFunc

def testFunc(x: HttpResponse): String = {
  Unmarshal(x).to[String].toString
}

这里的类型是可以的,但你在里面做的不是。

Unmarshal(x).to[String]

返回Future[String]- 表示它是异步结果,它的值会及时出现在那里。可以,在flatMap.

val sqrts: Double => List[Double] = x => List(Math.sqrt(x), -Math.sqrt(x))
val numbers = List(4.0, 9.0, 16.0)
numbers.flatMap(sqrts) // List(2.0, -2.0, 3.0, -3.0, 4.0, -4.0)
// results equal to
numbers
  .map(sqrts) // List(List(2.0, -2.0), List(3.0, -3.0), List(4.0, -4.0))
  .flatten    // List(2.0, -2.0, 3.0, -3.0, 4.0, -4.0)

在这里您可以看到 flatMap 的工作方式类似于 map + flatten(除了某些容器​​甚至不必实现 flatten,例如Future;))。

但为什么你的testFunc失败?基本上,您获取异步结果(Future[String])并且您不等待结果 - 您调用 toString 代替它只打印一些无用FulfilledFuture(You just accessed hello)的信息()而不是结果本身。

要解决此问题,您必须执行以下操作:

def testFunc(x: HttpResponse): String = {
  Await.result(Unmarshal(x).to[String], 10.seconds)
}

这将阻塞并最多等待 10 秒以使结果同步。(在这种情况下,这种方式超出了目的,map如果您计算的结果首先是同步的,那么它会更有用。)

于 2017-02-20T09:42:10.393 回答