https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

CLOVIS

04/10/2020, 12:48 PM
I'd like to implement a coroutine that implements a cache of values, indexed by ID (an Int). So far I have:
suspend fun <T> cache(requests: ReceiveChannel<Pair<Int
,
Copy code
SomeKindOfFuture<T>>> {
  val cache = mutableMapOf<Int, T>()
Copy code
for (request in requests) {
    ...
  }
}
But now I'm stuck. What I would like is that if the value is not in the cache, an expensive calculation is started, but I don't want the `cache`function to block nor suspend: if the calculation is started, I still want the cache to be able to reply to other requests, so I can't do something like:
Copy code
if (request.first in cache)
  request.second.complete(cache[request.first])
else {
  cache.add(request.first, launch { someCalculation(request.second) }.await())
}
I'm starting to think the best solution would be that the cache could receive either a ‘get' or ‘set' request, and when receiving a ‘get' that does not exists, it would create a new coroutine which would do the calculation and then send a ‘set' request, so the cache could continue processing requests in the meantime? What do you think?
d

Dennis

04/10/2020, 2:13 PM

https://youtu.be/a3agLJQ6vt8

around 29minutes, I think it might be similar to your Problem have a look
c

CLOVIS

04/10/2020, 6:08 PM
Thanks ^^ I'll do that
10 Views