简体   繁体   English

Scala:拦截函数,用于为Akka Futures提供隐式参数

[英]Scala: Intercept functions to provide implicit parameters with Akka Futures

Ok, so I have a series of calls to functions that return Akka Futures, and I'm chaining them by using flatMap and map like so: 好的,所以我有一系列调用返回Akka Futures的函数,并且我通过使用flatMap和map来链接它们:

doAsyncCall(..).flatMap { res1 =>
  doAsyncCall2(..).flatMap { res2 =>
    doAsyncCall3(..).map { res3 =>
      res
    }
  }
}

which can be spread out across different function calls. 它可以分散在不同的函数调用中。 Now each of these doAsyncCallX calls returns a Future[Result], and I would like to be able to compose these results, passing them over on the chain until in the end I can return the composed result of all the results in the chain. 现在每个doAsyncCallX调用返回一个Future [Result],我希望能够组合这些结果,将它们传递到链上,直到最后我可以返回链中所有结果的组合结果。

To do this, I thought of having each doAsyncCallX receive an implicit parameter of the previous result and combine the obtained result with the previous one. 为此,我想到让每个doAsyncCallX接收前一个结果的隐式参数,并将获得的结果与前一个结果相结合。 The problem is that I cannot see a way of doing this without littering the usage of my library with implicit vals like this: 问题是,我没有看到这样做的方法,而不会乱丢我的库的使用与这样的隐式val:

doAsyncCall(..).flatMap { res1 =>
  implicit val implicitRes1 = res1
  doAsyncCall2(..).flatMap { res2 =>
    implicit val implicitRes2 = res2
    doAsyncCall3(..).map { res3 =>
      res
    }
  }
}

What I would like to do is be able to intercept the application of flatMap to make sure that the previous response is passed correctly as the implicit parameter of the next doAsyncCallX call. 我想要做的是能够拦截flatMap的应用程序,以确保先前的响应作为下一个doAsyncCallX调用的隐式参数正确传递。 Any idea on how to accomplish this? 有关如何实现这一点的任何想法?

Perhaps I'm missing something, but is there a reason to use implicits at all? 也许我错过了一些东西,但有没有理由使用隐含的东西?

for(res1 <- doAsyncCall1(..);
    res2 <- doAsyncCall2(res1);
    res3 <- doAsyncCall3(res2)) yield(res3)

If you need to return a result composing multiple of the intermediate results, change the yield to yield something different, perhaps a tuple, like yield((res1,res2,res3)) . 如果需要返回组成多个中间结果的结果,请更改yield以产生不同的结果,可能是一个元组,如yield((res1,res2,res3)) The result of which would be something like Future[(Result1,Result2,Result3)] 其结果将类似于Future[(Result1,Result2,Result3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM