1

I'm using CaffeineCache together with memoizeF to cache the result of an operation that takes a case class as an input, like this:

    case class Foo(id: UUID, bar: String)

    implicit val myCache: CaffeineCache[Foo] =
      buildCache(cacheConfig.size) //builds the CaffeineCache

    def cachedOperation(foo: Foo): Future[Foo] =
      memoizeF(cacheConfig.duration) {
        // do something with foo and return it
      }

Now, in some cases I need to explicitly delete a specific element from the cache.

I think I could use myCache.doRemove(key) but from what I see in the ScalaCache documentation, when using memoizeF the key will be generated "from the class name, the name of the enclosing method, and the values of all of the method’s parameters" and I don't think backwards-engineering key from that and using it with doRemove is a good idea.

Is there another way of removing a specific element from the cache, if it was inserted using memoizeF? Or perhaps, could I in some way tell memoizeF to use id from Foo as the key instead of generating it from the class name etc (I know for certain that ids will be unique for every Foo instance)?

Perhaps using memoizeF is not a good idea at all for this scenario and I should go back to inserting to the cache "manually"? Any input is appreciated. I've looked in the official documentation and googled around but with no luck.

1 Answer 1

2

Cache[F[_], V] trait has explicit caching method where you can specify key for cache: https://github.com/cb372/scalacache/blob/master/modules/core/src/main/scala/scalacache/CacheAlg.scala#L56

So you can do:

case class Foo(id: UUID, bar: String)

val myCache: CaffeineCache[Foo] = buildCache(cacheConfig.size) //builds the CaffeineCache

def cachedOperation(foo: Foo): Future[Foo] =
   myCache.caching(foo)(cacheConfig.duration) {
        // do something with foo and return it
   }

def removeCache(foo: Foo): Future[Unit] = myCache.remove(foo)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this was exactly what I needed! Just making a note here that cachingF can be used to replace memoizeF- I think I wasn't clear in my original post that the "do something with foo" returned a future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.