https://kotlinlang.org logo
Title
b

benkuly

10/01/2021, 5:25 PM
I want to use
MutableStateFlow
as a cache for a database (sqldelight). It means, that e. g. I have
fun getKeysForUser(userId:String):MutableStateFlow<Keys?>
, which first looks in the cache (just a MutableMap) if it contains a matching MutableStateFlow and if not, creates one with an initial value from the database. It then also launches a coroutine to collect from the MutableStateFlow and write to the database on changes. If there are no subscribers anymore (except from the db-collect), I want to remove it from the cache. What is the best way to do it and does this whole idea work?
c

CLOVIS

10/01/2021, 7:56 PM
I implemented more or less exactly that: https://gitlab.com/braindot/clovis/-/blob/master/core.primitives/src/commonMain/kotlin/clovis/core/cache/MemoryCache.kt To read the code, Ref is a class that stores both an ID and has a suspend method to perform the request
The basic principles are unit tested and it seems to work fine, but there might be issues lurking