How would you guys wrap a `Callable` in a coroutin...
# coroutines
e
How would you guys wrap a
Callable
in a coroutine?
j
What do you mean exactly? You want to run a coroutine that asynchronously executes the
Callable
? What is your goal more precisely?
e
I have a Cache that uses a Java
get(K key, Callable<V> valueLoader
) but I would like to be able to call it with this signature:
suspend fun get(key: K, valueLoader: suspend () -> V
)
j
The first part of the problem is that the original method calls the
Callable
in a synchronous way. It blocks its current thread in order to get the value, so there is no way you can provide this value asynchronously and lazily at the same time. The solution for this part would be to use `runBlocking`:
Copy code
fun get(key: K, valueLoader: suspend () -> V) = get(key, Callable { runBlocking { valueLoader() } })
You wanted your new function to be
suspend
probably because you want to express the asynchronism for this. The problem is that the original
get
is synchronous, so you cannot really wait for its value in a suspending way. With
runBlocking
, you don't really have to anyway.
s
If you use an async cache like Caffeine, you can make the whole thing fully asynchronous
My current best attempt for how to do it is in this StackOverflow answer
e
I'll try Caffeine, currently I'm using this one https://github.com/dropbox/Store/tree/main/cache
s
It should be very familiar since it looks like both are based on Guava
e
I see, it's a lot of code to get a Kotlin cache working that's synchronised by key
Thanks for info
203 Views