Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove class cast #27

Open
AlexeyKorshun opened this issue Jan 18, 2019 · 2 comments
Open

Remove class cast #27

AlexeyKorshun opened this issue Jan 18, 2019 · 2 comments

Comments

@AlexeyKorshun
Copy link

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.

@RubyLichtenstein
Copy link
Owner

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
Copy link
Owner

@AlexeyKorshun PR is more then welcome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants