Search code examples
scalacachingmemoizationcaffeine-cache

Scalacache delete from cache set up with memoizeF


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.


Solution

  • 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)