project reactor - How to return a Mono with a long running task inside map? -
i want transform data inside map function of mono:
long result = 0.0; return mono.just(result).map(value -> { // long running transformation here // , assign result (maybe 5 seconds task) // in our case request: mono<result> resultobject = service.getresult(); resultobject.subscribe(new subscriber<result>() { @override public void onsubscribe(subscription s) { system.out.println("subscribe: " + system.currenttimemillis()); s.request(1); } @override public void onnext(result result) { system.out.println("on next: " + system.currenttimemillis()); value = result.getvalue(); // not 0.0 } @override public void onerror(throwable t) { system.out.println("error " + t); } @override public void oncomplete() { system.out.println("complete"); } }); return value; });
if call 0.0
result returning before map function done. me not make sense. how else supposed transform result before returning it?
edit
i following in opinion not optimal solution:
final countdownlatch latch = new countdownlatch(1); long result = 0.0; return mono.just(result).map(value -> { // long running transformation here // , assign result (maybe 5 seconds task) // in our case request: mono<result> resultobject = service.getresult(); resultobject.subscribe(new subscriber<result>() { @override public void onsubscribe(subscription s) { system.out.println("subscribe: " + system.currenttimemillis()); s.request(1); } @override public void onnext(result result) { system.out.println("on next: " + system.currenttimemillis()); value = result.getvalue(); // not 0.0 latch.countdown(); } @override public void onerror(throwable t) { system.out.println("error " + t); } @override public void oncomplete() { system.out.println("complete"); } }); try { latch.await(); return value; } catch(interruptedexception e) { e.printstacktrace(); return -1.0; } });
that sounds flatmap
for: if long running task asynchronous , can represented publisher<t>
can triggered asynchronously flatmap
.
note mono#flatmap(function)
called mono#then(function)
in 3.0.x
.
so in 3.0.7:
mono.just(param).then(p -> service.getresult(p));
and in 3.1.0.m3:
mono.just(param).flatmap(p -> service.getresult(p));
note if don't use value (service doesn't have parameter) can provide continuation mono
, using then(mono)
(which valid in both 3.0.x , 3.1.x):
mono.just(paramthatgetsignored).then(service.getresult());
(but in case starting point of mono.just(...)
isn't terribly relevant)
Comments
Post a Comment