All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.tech.skot.model.SKManualDataWithCache.kt Maven / Gradle / Ivy

There is a newer version: 1.2.9
Show newest version
package tech.skot.model

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.KSerializer
import tech.skot.core.SKLog


abstract class SKManualDataWithCache(
    private val name: String,
    private val serializer: KSerializer,
    private val key: String? = null,
    private val cache: SKPersistor = globalPersistor,
    private val initialDefaultValue: D
) : SKData {

    override val flow: MutableStateFlow?> = MutableStateFlow(null)
    override val defaultValidity = Long.MAX_VALUE
    override val _current: DatedData?
        get() = flow.value


    private val initMutex = Mutex()

    private suspend fun initWithCache() {
        initMutex.withLock {
            if (flow.value == null) {
                val cachedDatedData = cache.getDateOfData(name, key)?.let { cacheDate ->
                    try {
                        cache.getData(serializer, name, key)?.let { DatedData(it, cacheDate) }
                    } catch (ex: Exception) {
                        SKLog.e(
                            ex,
                            "SKManualDataWithCache Problème à la récupération du cache de la donnée $name $key"
                        )
                        null
                    }
                }
                flow.value = cachedDatedData ?: DatedData(initialDefaultValue, 0)
            }
        }
    }

    override suspend fun fallBackValue(): D? {
        if (flow.value == null) {
            initWithCache()
        }
        return _current?.data
    }

    override suspend fun get(validity: Long?): D {
        if (flow.value == null) {
            initWithCache()
        }
        return super.get(validity)
    }


    fun setValue(newValue: D) {
        flow.value = DatedData(newValue)
        CoroutineScope(Dispatchers.Default).launch {
            try {
                cache.putData(
                    serializer = serializer,
                    name = name,
                    data = newValue,
                    key = key
                )
            }
            catch (ex:Exception) {
                SKLog.e(ex, "SKManualDataWithCache Problème à la mise en cache de la donnée $name $key")
            }
        }


    }

    override suspend fun update(): D {
        if (flow.value == null) {
            initWithCache()
        }
        return _current?.data ?: initialDefaultValue
    }


}






© 2015 - 2024 Weber Informatics LLC | Privacy Policy