简体   繁体   中英

How to save method returned mono in Reactor's Context to use it the next time the method is called in this reactor stream?

I have a method that returns data from some repo. Of course - these data can be changed at any given moment. I want to ensure that the data returned from the method remains consistent during a chain of operations (the method can also be called from another component during the chain). for example:

fetchDataThanCanBeChanged()
.flatMap(...)
.doOnNext(...)
.doOnSuccess(...)
.map(...)
.zipWith(...)
.flatMap(...)
.then(fetchDataThanCanBeChanged())......

I want to be sure that the second call to fetchDataThanCanBeChanged() returns the same data as the first. I tried to wrap fetchDataThatCanBeChanged with method with Mono.deferContextual:

private Mono<Object> fetchDataUsingCache() {
   return fetchDataThatCanBeChanged()
      .flatMap(s ->
      Mono.deferContextual(ctx -> {
        System.out.println("cached snapshot=" + ctx.getOrEmpty("KEY")); 
        return Mono.just(s);
      }).contextWrite(ctx ->
          ctx.put("KEY", ctx.getOrDefault("KEY", s))
      ));
}

and call it twice:

fetchDataUsingCache()
.flatMap(d -> change(d))
.doOnNext(p -> saveChangedDataInRepo(p))
.delayElement(Duration.ofMillis(2000))
.fetchDataUsingCache()
.block();

but the content of fetchDataThatCanBeChanged() is only executed once and the returned data is the updated.

any idea for a solution??? Many thanks in advance!

finally I wrapped my code where I need the old fetched data with Mono.deferContextual and wrote the data to context like that:

fetchDataThanCanBeChanged()
   .flatMap(s -> Mono.deferContextual(ctx -> 
    changeDataInRepo()
    .doOnSuccess(b -> fetchDataThanCanBeChanged())
    .thenReturn(doWhateverNeedWithOldData(ctx.getOrEmpty("KEY"))))
  .contextWrite(ctx -> ctx.put("KEY", s))))
.block();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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