DiskCache - Simple and readable disk cache for kotlin and android applications

Related tags

Utility DiskCache
Overview

DiskCache

Simple and readable disk cache for kotlin and android applications (with journaled lru strategy)

This is a simple lru disk cache, based on the idea of the original DiskLruCache but realized in modern kotlin and with some semplifications (not less functions!). It doesn't use any exernal library, and has a good recovery and fault tollerance.

To use this library in your projects, two easy step are required, the first on your main build.gradle and the second in your module level build.gradle:

allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}

dependencies {
        implementation 'com.github.giovcorte:DiskCache:1.2'
}

Example of usages in a wrapper class for storing and retrieving bitmaps:

class ImageDiskCache(private val diskCache: DiskCache) {

    fun get(key: String): Bitmap? {
        var bitmap: Bitmap? = null
        diskCache.get(key)?.let { snapshot ->
            bitmap = BitmapFactory.decodeStream(FileInputStream(snapshot.file()))
            snapshot.close()
        }
        return bitmap
    }

    fun contains(key: String): Boolean {
        return diskCache.get(key) != null
    }

    fun put(key: String, bitmap: Bitmap) {
        diskCache.edit(key)?.let { editor ->
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, FileOutputStream(editor.file()))
            editor.commit()
        }
    }

    fun clear() {
        diskCache.evictAll()
    }

}

Like the original DiskLruCache, we have to open and close Editors for modifying a file and Snapshots for reading. You can open multiple Snapshots but only one Editor at time. When you have finished to edit/read the file, you have to commit() the changes or close() the Sanpshot, so the entry can be saved or, in case of a last recentry used entry, deleted if space cleanup is required. A difference form the original is that this cache expose the file you store, and not an InputStream/OutputStream. Also the keys must match the [a-zA-Z0-9] regex. In the Utilsclass you will find a method to format your keys.

If you dont want to use directly the DiskCache there are availables three tipes of cache wrappers: AsyncDiskCache, based on susped coroutine functions; SyncDiskCache, with synchronous operations; and CallbackDiskCache, where you provide the function callback for the operation. You can implement each of those abstract classes giving two methods, one for decoding the T type variable from a file and another to write your T value to it. Example implementation for images:

class AsyncImageDiskCache(diskCache: DiskCache): AsyncDiskCache(diskCache) {

    override fun writeValueToFile(value: Bitmap, file: File) {
        value.compress(Bitmap.CompressFormat.PNG, 100, FileOutputStream(file))
    }

    override fun decodeValueFromFile(file: File): Bitmap? {
        return BitmapFactory.decodeStream(FileInputStream(file))
    }

}

Example of AsyncDiskCache usage:

val value: T? = async { 
    cache.get(key)
}
value.await()
	

Example of CallbackDiskCache usage:

cache.get(key) { tValue ->
	// use your value               
}
	
cache.put(key, value) { booleanSuccess ->
	// use the operation result
}
You might also like...
Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platform the code is running.

Trail Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platfor

Create a simple and more understandable Android logs.
Create a simple and more understandable Android logs.

DebugLog Create a simple and more understandable Android logs. #Why? android.util.Log is the most usable library of the Android. But, when the app rel

✔️ Secure, simple key-value storage for Android
✔️ Secure, simple key-value storage for Android

Hawk 2.0 Secure, simple key-value storage for android Important Note This version has no backward compatibility with Hawk 1+ versions. If you still wa

A Simple Android Library for Kenyan Counties

A Simple Android Library for Kenyan Counties

A small library which will save you from writing the same intent creation code again and again for the most simple tasks

Android Intents A small library which will save you from writing the same intent creation code again and again for the most simple tasks. I found myse

A simple library for validating user input in forms using annotations.
A simple library for validating user input in forms using annotations.

ValidationKomensky for Android A simple library for validating user input in forms using annotations. Features: Validate all views at once and show fe

Ask Permission - Simple RunTime permission manager

Ask Permission https://kishanjvaghela.github.io/Ask-Permission/ Simple RunTime permission manager How to use Add url to your gradle file compile 'com.

A helper library to ease the most repetitive codes with simple reusable attributes.

ak-universal-android-helper A helper library to ease the most repetitive codes with simple reusable attributes. AKUAH can help you with many repetitiv

Format numbers using a string pattern with this simple number formatted like ##-####-##

AndroidPattern Format numbers using a string pattern with this simple number formatted like ##-####-## Installation To get a Git project into your bui

Releases(1.3)
Owner
Giovanni Corte
Giovanni Corte
Android library to easily serialize and cache your objects to disk using key/value pairs.

Deprecated This project is no longer maintained. No new issues or pull requests will be accepted. You can still use the source or fork the project to

Anup Cowkur 667 Dec 22, 2022
Java implementation of a Disk-based LRU cache which specifically targets Android compatibility.

Disk LRU Cache A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key and a fixed number of values. Each key m

Jake Wharton 5.7k Dec 31, 2022
Keep data as a linked list on disk. A alternative way to reduce redundant operation for DiskLruCache

DiskLinkedList Keep data as a linked list on disk. An alternative way to reduce redundant operation for DiskLruCache Use-case Android have build-in Di

Cuong V. Nguyen 6 Oct 29, 2021
a simple cache for android and java

ASimpleCache ASimpleCache 是一个为android制定的 轻量级的 开源缓存框架。轻量到只有一个java文件(由十几个类精简而来)。 1、它可以缓存什么东西? 普通的字符串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java对象,和 b

Michael Yang 3.7k Dec 14, 2022
A simple Android utils library to write any type of data into cache files and read them later.

CacheUtilsLibrary This is a simple Android utils library to write any type of data into cache files and then read them later, using Gson to serialize

Wesley Lin 134 Nov 25, 2022
A Virtual Machine For Assessing Android applications, Reverse Engineering and Malware Analysis

Androl4b AndroL4b is an android security virtual machine based on ubuntu-mate includes the collection of latest framework, tutorials and labs from dif

null 1k Dec 27, 2022
A set of helper classes for using dagger 1 with Android components such as Applications, Activities, Fragments, BroadcastReceivers, and Services.

##fb-android-dagger A set of helper classes for using dagger with Android components such as Applications, Activities, Fragments, BroadcastReceivers,

Andy Dennie 283 Nov 11, 2022
Simple-Claim-Form - Android App for creating a simple dynamic form with MVVM architecture

Simple-Claim-Form Android App for creating a simple dynamic form with MVVM archi

Shubham Gangpuri 1 Aug 14, 2022
nestegg - Very simple Kotlin caching library

nestegg - Very simple Kotlin caching library

Runner-be 4 Jun 15, 2022
A simple and easy to use stopwatch and timer library for android

TimeIt Now with Timer support! A simple and easy to use stopwatch and timer library for android Introduction A stopwatch can be a very important widge

Yashovardhan Dhanania 35 Dec 10, 2022