0

So I have an empty map referenced like:

private var labelsForGroupId: Map<GroupId, Label> = emptyMap()

to lower the amount of calls through network api. After first call I cache the response to the map.

However, I would love to add TTL to that map, (for example, every hour it should be empty again). I am quite new to Kotlin, so wondering what would be the best approach here with some examples?

vukojevicf
  • 609
  • 1
  • 4
  • 22
  • in spring you can use a [Scheduled](https://spring.io/guides/gs/scheduling-tasks/) task that will run at whatever interval you decide. – AlexT Aug 27 '21 at 10:33
  • Why not use one of the many existing caching facilities instead of reimplementing it from scratch? You can take a look at `@Cacheable` annotation, and choose a cache implementation that allows configuring a TTL: https://stackoverflow.com/questions/8181768/can-i-set-a-ttl-for-cacheable – Joffrey Aug 27 '21 at 11:14
  • I'm fine with any existing caching solutions, just didn't know how to implement it with my map. Again, kinda of Kotlin newbie – vukojevicf Aug 27 '21 at 11:30

1 Answers1

0

Instead of using a Map, you could use Guava Cache. It works like a Map (key-value) and have expiration policies.

Expiration by time example:

CacheBuilder.newBuilder()
  .expireAfterAccess(200, TimeUnit.MILLISECONDS)
  .build(loader);

If you are not interested in caches at all, then you could try to setup a Coroutine with a ScheduledExecutorService as Dispatcher. I never did this before but is a way out. Take a look at the Executors documentation - Coroutine context and dispatchers

  • If the given [ExecutorService] is an instance of [ScheduledExecutorService], then all time-related * coroutine operations such as [delay], [withTimeout] and time-based [Flow] operators will be scheduled * on this executor using [schedule][ScheduledExecutorService.schedule] method. If the corresponding * coroutine is cancelled, [ScheduledFuture.cancel] will be invoked on the corresponding future.
Gabriel Suaki
  • 321
  • 3
  • 6