scala - Play 2.5 preserve context in async calls -
in our controller class reach out service data :
future<jsonnode> futuresite = someclient.getsite(siteid, queryparams); return futureconverters.tojava(futuresite).thenapplyasync((sitejson) -> { site site = json.fromjson(sitejson, site.class); try { return function.apply(site); } catch (requestexception e) { return e.result; } }).exceptionally(throwable -> { if(throwable instanceof ourclientexception) { if(((ourclientexception) throwable).httpstatuscode == 404) { return entitynotfound("site", siteid); } } return null; });
what notice context set in unit tests (we use scalatest-play) lost , becomes null after make async call (futureconverters.tojava(futuresite).thenapplyasync((sitejson)
, t on separate thread.
which causes problem down in controller code, use above function ... request() throw runtime exception saying there no context available.
how can preserve context ?
you should inject play.libs.concurrent.httpexecutioncontext controller , specify current context second argument completionstage#thenapplyasync(..,..).
public class application extends controller { @inject httpexecutioncontext ec; public completionstage<result> index() { somecompletablefuture.supplyasync(() -> { // request() }, ec.current()); }}
p.s. https://www.playframework.com/documentation/2.5.x/javaasync#using-completionstage-inside-an-action
Comments
Post a Comment