1

I have the following code:

final T savedEntity = repository.save(entity);
entityCacheService.putIntoCache(entity.getId(), savedEntity);

Now I made my repository reactive. My question is how to make the cache store now mono and flux.

final Mono<T> savedEntity = repository.save(entity);
entityCacheService.putIntoCache(entity.getId(), <<What here>>);

I came across the following Mono and Flux Caching but it's only for lookup and since I am also a beginner in reactive programming.

halfer
  • 19,824
  • 17
  • 99
  • 186
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

1 Answers1

1

The best way in your case is to rely on the fact that the save operation returns a Mono<T> that emits the saved entity.

You could thus use doOnNext to also put that entity in the cache whenever it is saved in DB:

final Mono<T> savedEntity = repository.save(entity)
    .doOnNext(entity -> entityCacheService.putIntoCache(entity.getId(), entity);

The resulting Mono<T> will both save then cache the entity whenever it is subscribed to.

Simon Baslé
  • 27,105
  • 5
  • 69
  • 70
  • Thank you for your answer. For flux can i do like following `savedEntities.collectList().doOnNext(e -> e.stream().forEach(c -> entityCacheService.putIntoCache(c.getId(), c)));` if `savedEntities` is Flux – Saurabh Kumar Apr 03 '18 at 14:38
  • No, doOnEach will be invoked for each saved entity so it is already doing a job similar to forEach – Simon Baslé Apr 03 '18 at 15:00
  • you mean like following `savedEntities.doOnEach(s -> { if (s.isOnNext()) { T e = s.get(); entityCacheService.putIntoCache(e.getId(), e); } });` ? – Saurabh Kumar Apr 03 '18 at 18:56
  • Ah sorry i meant doOnNext like in my first example – Simon Baslé Apr 04 '18 at 10:14