Kotlin-Multiplatform-Firebase icon indicating copy to clipboard operation
Kotlin-Multiplatform-Firebase copied to clipboard

Remove class cast

Open AlexeyKorshun opened this issue 6 years ago • 2 comments

https://github.com/RubyLichtenstein/Kotlin-Multiplatform-Firebase/blob/master/common-all/src/commonMain/kotlin/rubylich/ktmp/base/BaseRepo.kt#L28

What will be, if I want serialize not Post class instance. I think you can create interface for serialize, and check that class is implement it.

AlexeyKorshun avatar Jan 18 '19 09:01 AlexeyKorshun

Right, further more the serializer can be fully generic and without reflection

class DataCache<T : Any>(
    context: Context,
    val serializer: KSerializer<T>,
    val clazz: Class<T>
) {
    val myJSON =
        JSON.apply { install(SimpleModule(Timestamp::class.java.kotlin, TimestampSerializer)) }

    private val maxSize = 1000
    private val diskPath = "FirestoreCoroutines"

    private val composedCache: Cache<String, String>

    init {
        val memoryCache: Cache<String, String> = Cache.createLruCache(maxSize)
        val cacheFile = File(context.filesDir, diskPath)

    suspend fun get(key: String): T? =
        composedCache.get(key).await()?.let {
            myJSON.nonstrict.parse(serializer, it)
        }

    suspend fun getList(key: String): List<T>? =
        composedCache.get(key).await()?.let {
            myJSON.nonstrict.parse(serializer.list, it)
        }

    suspend fun set(key: String, value: T) {
        try {
            composedCache.set(key, myJSON.nonstrict.stringify(serializer, value)).await()
        } catch (e: Throwable) {
            Timber.e(e)
        }
    }

    suspend fun setList(key: String, value: List<T>) {
        try {
            composedCache.set(key, myJSON.nonstrict.stringify(serializer.list, value)).await()
        } catch (e: Throwable) {
            Timber.e(e)
        }
    }
}

RubyLichtenstein avatar Jan 18 '19 12:01 RubyLichtenstein

@AlexeyKorshun PR is more then welcome

RubyLichtenstein avatar Jan 18 '19 12:01 RubyLichtenstein