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

Introduce default creation method/setting, instead of always requiring lambda at getOrPut #128

Open
carstenhag opened this issue Sep 4, 2023 · 2 comments
Labels
enhancement New feature or request

Comments

@carstenhag
Copy link

Is your feature request related to a problem? Please describe.
I want to create a bitmap cache (ie val bitmapCache = InMemoryKache<Int, Bitmap>).
If I run bitmapCache.get(1) I want to get the data. If it doesn't exist, it should automatically run a suspending function first, then return the value.

getOrPut theoretically does this, but I would have to tediously copy over the creationFunction function to all places where I want to get values.

Describe the solution you'd like
The Configuration could accept a factory lambda.

Describe alternatives you've considered
Define a lambda like this once, and reference it in all getOrPut calls:

    val bitmapConstruction = { resId: Int ->
        bitmapHelper.getBitmap(resId, context)
    }
    bitmapCache.getOrPut(R.drawable.xyz, bitmapConstruction)

Additional context
LruCache has a way to override the create method to do just this. But it's written in Java and doesn't support coroutines etc.

@carstenhag carstenhag added the enhancement New feature or request label Sep 4, 2023
@carstenhag
Copy link
Author

As I didn't need to make the cache public anyway, I implemented it like this:

    private val bitmapConstructionLambda = { resId: Int ->
        bitmapHelper.getBitmap(resId, context)
    }
    private val cacheSize = 4 * 1024 * 1024L // 4 MB
    private val bitmapCache = InMemoryKache<Int, Bitmap>(maxSize = cacheSize) {
        sizeCalculator = { _, y -> y.byteCount / 1024L }
    }

    override suspend fun getCachedBitmap(@DrawableRes resId: Int): Bitmap {
        val bitmap = bitmapCache.getOrPut(resId, bitmapConstructionLambda)
        require(bitmap != null) { "Bitmap for $resId could not be get or created" }
        return bitmap
    }

@MSDarwish2000
Copy link
Member

Thank you for your valuable feedback and suggestion. I think this feature is a good-to-have one and I'd think of ways to implement it in a future version.

I apologize for the late response for personal reasons.

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

No branches or pull requests

2 participants