• Stars
    star
    156
  • Rank 238,218 (Top 5 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

In mobile development exists solution for caching with RxJava usage, but there is no solutions for Kotlin Coroutines. The project is to provide this functionality to mobile community.

CoroutinesCache

Build Status

Preview

The goal of this library is simple: caching your data models like Picasso caches your images, with no effort at all.

Every Android application is a client application, which means it does not make sense to create and maintain a database just for caching data.

Plus, the fact that you have some sort of legendary database for persisting your data does not solves by itself the real challenge: to be able to configure your caching needs in a flexible and simple way.

Inspired by Retrofit api, CoroutinesCache is a reactive caching library for Android and Kotlin which turns your caching needs.

To get full information about how library works follow next article:

https://proandroiddev.com/caching-with-kotlin-coroutines-7d819276c820

Note

Coroutines Cache works only on kotlin-coroutines:0.26.1 and above.

Getting started

Library is located in jcenter, add jcenter repository in main gradle file

allprojects {
  repositories {
    ...
    jcenter()
  }
}

Grab via Gradle:

  implementation 'com.epam.coroutinecache:coroutinecache:0.9.6'

or Maven:

  <dependency>
    <groupId>com.epam.coroutinecache</groupId>
    <artifactId>coroutinecache</artifactId>
    <version>0.9.6</version>
    <type>pom</type>
  </dependency>

Usage

To start use cache you need to create CoroutinesCache object:

val coroutinesCache = CoroutinesCache(cacheParams: CacheParams, scope: CoroutineScope)

CacheParams defines cache location, json mapper and persistence size in Mb.

First param of CacheParams is max size that could be saved in persistence in Mb.

Second param is JsonMapper interface that provides one of several implementation: GsonMapper, JacksonMapper, MoshiMapper. For each of those mappers you need to add appropriate dependency in build.gradle file.

Last param is directory where cache files will be stored. Be sure that directory exists and you has write permission there, otherwise you will get IllegalStateException

class CacheParams (maxPersistenceCacheMB: Int, mapper: JsonMapper, directory: File)

Next step you need to create an interface with functions that will describe data, which should be stored. For each function you can add params by next annotations:

  1. @ProviderKey(key: String, entryClass: EntryClass) - key that will be used for saving data, entryClass it is an another annotation @EntryClass(rawType: KClass<*>, vararg typeParams: EntryClass = []) that used to specify value's type needed for serialization/deserialization (to avoid obtaining type through reflection). typeParams used when you need parameterized type, such annotation for list should looks like: EntryClass(List::class, EntryClass(Data::class))
  2. @LifeTime(value: Long, timeUnit: TimeUnit) - value describes how long record should be stored in memory or persistence. If this annotation isn't set, record will be stored without time limit
  3. @Expirable - Set expirable param to true. If this annotation isn't set it means that record could be deleted from persistence, even it hasn't reached life limit in persistence low memory case.
  4. @UseIfExpired - If this annotation is set it means that data will be retrieved from cache even if record reached its lifetime. Could be used only once, after getting, record will be deleted from cache.

Note: In cases when data can be requested without any parameters you may use a method that should be a suspend function containing only one param that is also a suspend function without params that returns type T. It's result will be stored in the cache. And function's return value also should be In case, when you data request call requires some parameters and also you want to store data with different keys that depend on call parameters, then you should use a suspend method that takes an implementation of ParameterizedDataProvider interface. In that case data will be stored under modified key that is controlled by your implementation of parameterizeKey method.

To connect interface and CoroutinesCache and your interface just call CoroutinesCache.using(YourInterface::class.java). This method will return interface instance. To save and get data from cache just call methods from returned instance of your interface.

Example 1 (no parameters)

CacheProviders

interface CacheProviders {
    @ProviderKey("TestKey", EntryClass(Data::class))
    @LifeTime(value = 1L, unit = TimeUnit.MINUTES)
    @Expirable
    @UseIfExpired
    suspend fun getData(dataProvider: suspend () -> Data): Data
}

Repository

class Repository (private val cacheDirectory: File) {
     private val coroutinesCache = CoroutinesCache(CacheParams(10, GsonMapper(), cacheDirectory))
     private val restApi = Retrofit...create(RestApi::class.java)
     private val cacheProviders = coroutinesCache.using(CacheProviders::class.java)
     
     suspend fun getData(): Data = cacheProviders.getData(restApi::getData)
}

MainActivity

class MainActivity : AppCompatActivity() {
    private val persistence by lazy { Repository(cacheDir) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        GlobalScope.launch (Dispatchers.Main) {
            val data = persistence.getData()
            messageView.text = data.toString()
        }
    }
}

Example 2 (with parameters)

CacheProviders

interface CacheProviders {
    @ProviderKey("BaseKey", EntryClass(Data::class))
    @LifeTime(value = 1L, unit = TimeUnit.MINUTES)
    @Expirable
    @UseIfExpired
    suspend fun getParameterizedData(provider: ParameterizedDataProvider<Data>): Data
}

Repository

class Repository (private val cacheDirectory: File) {
     private val coroutinesCache = CoroutinesCache(CacheParams(10, GsonMapper(), cacheDirectory))
     private val restApi = Retrofit...create(RestApi::class.java)
     private val cacheProviders = coroutinesCache.using(CacheProviders::class.java)

     suspend fun getParametrizedData(search: String): Data = cacheProviders.getParameterizedData(DataProviderImpl())

     private inner class DataProviderImpl(private val search: String) : ParameterizedDataProvider<Data> {

          override suspend fun getData(): Data = restApi.getParameterizedData(search)

          override fun parameterizeKey(baseKey: String): String = "${baseKey}_$search"
     }
}

MainActivity

class MainActivity : AppCompatActivity() {
    private val persistence by lazy { Repository(cacheDir) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        GlobalScope.launch (Dispatchers.Main) {
            val data = persistence.getParameterizedData("Hello world!")
            messageView.text = data.toString()
        }
    }
}

To see full example, check app module in this repository.

ProGuard

Do not forget to keep your own data classes in proguard rules. For example, add this line for 'Data' class that is being cached with this library:

# Keep all of your data classes that are stored in CoroutineCache
-keep class com.epam.example.coroutinescache.Data { *; }

Also, please add following instructions so that CoroutineCache may work properly:

# ProGuard instructions that are required for CoroutineCache to work properly
-keepclassmembers enum com.epam.coroutinecache.core.Source {
    public *;
}

More Repositories

1

ketcher

Web-based molecule sketcher
TypeScript
464
star
2

mriviewer

MRI Viewer is a high performance web tool for advanced 2-D and 3-D medical visualizations.
JavaScript
323
star
3

Indigo

Universal cheminformatics toolkit, utilities and database search tools
C++
295
star
4

lib-obj-c-attr

Attributes for your code
Objective-C
181
star
5

UUI

React-based components and accelerators library built by EPAM Systems.
TypeScript
167
star
6

NGB

New Genome Browser (NGB) - a Web - based NGS data viewer with unique Structural Variations (SVs) visualization capabilities, high performance, scalability, and cloud data support
Java
160
star
7

OSCI

Open Source Contributor Index
Python
157
star
8

cloud-pipeline

Cloud agnostic genomics analysis, scientific computation and storage platform
Java
144
star
9

JDI

Try JDI Light https://github.com/jdi-testing/jdi-light
Java
143
star
10

nfstrace

Network file system monitor and analyzer
C++
139
star
11

miew

3D Molecular Viewer
JavaScript
131
star
12

CoroutinesExtensions

To modify data RxJava provides a lot of methods, but Kotlin Coroutines doesn’t have them. This library’s goal is creating functions that will provide users possibility to use the same functional as in RxJava
Kotlin
79
star
13

edp-install

Start from the EPAM Delivery Platform main page. This repository contains the Helm Chart templates that describe the installation of the main configuration (e.g. database registration, user creation in a database, etc.), which cannot be subsumed to the corresponding operator or allotted to the repository
Smarty
79
star
14

java-cme-mdp3-handler

Java Market Data Handler for CME Market Data (MDP 3.0)
Java
74
star
15

parso

lightweight Java library designed to read SAS7BDAT datasets
Java
72
star
16

aws-syndicate

Syndicate deployment framework
Python
57
star
17

road-ios-framework

ROAD – Rapid Objective-C Applications Development
Objective-C
56
star
18

pipeline-builder

Pipeline Builder is a JavaScript library for visualizing and constructing bioinformatics workflows, using Workflow Description Language (WDL)
JavaScript
55
star
19

Wilma

Service Virtualization Solution – a combined Service Stub and Transparent Proxy
Java
52
star
20

ai-dial-core

The main component of AI DIAL, which provides unified API to different chat completion and embedding models, assistants, and applications
Java
50
star
21

ai-dial-chat

A default UI for AI DIAL
TypeScript
46
star
22

sitecore-headless-commerce-accelerator

EPAM Headless Commerce Accelerator for Sitecore Experience Commerce
C#
38
star
23

xframework

XFramework, or XF, is a small but powerful HTML5 JavaScript framework for building truly cross-platform web applications that will work on mobile phones, tablets, desktop computers, and even Smart TVs.
JavaScript
38
star
24

gflog

Highly efficient garbage-free logging framework for Java 8+
Java
37
star
25

SciGlass

The database contains a vast set of data on the properties of glass materials.
34
star
26

ai-dial

Documentation for AI DIAL
Jupyter Notebook
33
star
27

aws-ci-cd-accelerator

HCL
32
star
28

fix-antenna-net-core

FIX Antennaβ„’ .NET Core is a high-performance low latency .NET FIX Engine.
C#
32
star
29

badgerdoc

Python
32
star
30

eco-kafka-manager

Java
31
star
31

TimebaseCryptoConnectors

TimeBase Crypto Market Data Connectors
Java
31
star
32

edp-keycloak-operator

It is responsible for establishing a connection to provided Keycloak Server, reconciling realms, and clients according to the created CRs
Go
28
star
33

Android-Secure-Storage

Secure android storage to keep private information safe
Java
26
star
34

epam-graphql

C#
22
star
35

ai-dial-sdk

Framework to create applications and model adapters for AI DIAL
Python
22
star
36

Gepard

Test Automation Framework
Java
18
star
37

Indigo-ELN-v.-2.0

Indigo - The Open-Source Chemistry Electronic Lab Notebook
Dockerfile
16
star
38

lifescience

Documentation on EPAM Life Sciences open source solutions
CSS
16
star
39

sitecore-engx-scaffold

JavaScript
13
star
40

eco-schema-catalog

Eco Schema Catalog
Java
13
star
41

OneDrive-L

OneDrive for Business Linux client
Python
13
star
42

libdt

libdt
C
12
star
43

covid-resistance-mobile

COVID Resistance – Mobile
C#
12
star
44

wdl-workspace

Web-based User Interface to run WDL bioinformatics workflows using Cromwell server
JavaScript
11
star
45

headless-commerce-salesforce-accelerator

Headless Commerce Accelerator for Salesforce Commerce Cloud
JavaScript
11
star
46

TimebaseOrderBook

This library provides lightweight and garbage-free order book component for Java11+
Java
10
star
47

hubctl

Hub CTL is stack composition and lifecycle tool
Go
10
star
48

clocks

Web application which allows to create a dashboard with widgets that shows the time and time zones for selected locations
TypeScript
9
star
49

ai-dial-helm

EPAM AI DIAL Helm Repository
Smarty
9
star
50

TimebaseWS

TimeBase REST/WS backend
Java
8
star
51

fonda

Fonda is a framework which offers scalable and automatic analysis of multiple NGS sequencing data types
Java
8
star
52

ai-dial-adapter-openai

The project implements AI DIAL API for language models from Azure OpenAI
Python
8
star
53

edp-headlamp

Portal UI for the KubeRocketCI platform inspired by Headlamp
TypeScript
8
star
54

Imago

2D chemical structure image recognition toolkit
8
star
55

edp-sonar-operator

It installs the Sonar EDP Component on a cluster for continuous inspection of a codebase code quality
Go
8
star
56

ai-dial-assistant

Model agnostic assistant/addon implementation for AI DIAL. It allows to use self-hosted OpenAI plugins as DIAL addons
Python
8
star
57

hub-toolbox

Toolbox Docker image
Dockerfile
7
star
58

TimeBaseTutorial

TimeBase tutorial
Java
7
star
59

edp-cluster-add-ons

This repository contains a collection of pre-configured solutions for the KubeRocketCI Kubernetes Cluster deployments. It follows the GitOps methodology and utilizes the ArgoCD App of Apps pattern for streamlined configuration and deployment.
Python
7
star
60

Containers

Collection of handy data structures and algos for C#/Java specially designed for GC-free programming. ObjectPools, MutableBlobs, MutableStrings, BinaryHeaps, Linked Lists, Trees, fast memory copy, fast hash calculators and others.
C#
6
star
61

sdmxsource

Java
6
star
62

edp-library-pipelines

A Jenkins shared-library for the reference EDP pipelines
Groovy
6
star
63

covid-tracing-bluetooth-poc

Kotlin
6
star
64

JDI-Examples

Examples for JDI Framework
Java
6
star
65

ai-dial-adapter-bedrock

The project implements AI DIAL API for language models from AWS Bedrock
Python
6
star
66

ai-dial-adapter-vertexai

The project implements AI DIAL API for language models and embeddings from Vertex AI
Python
6
star
67

htsjdk-s3-plugin

HTSJDK plugin for multihreaded loading of SAM/BAM files stored in AWS S3
Java
6
star
68

ai-dial-ci

Continuous Integration instrumentation for AI DIAL components
6
star
69

edp-nexus-operator

It installs the Nexus EDP Component on a cluster to store/manage artifacts of codebases. It also exposes configuration that allows Nexus to perform with other EDP components
Go
6
star
70

ai-dial-chat-themes

Static content and UI customizations for default AI DIAL UI
Makefile
6
star
71

model_garden

EPAM accelerator to spread-up Computer Vision DataSet preparation for Machine Learning model training.
Python
5
star
72

TimeBaseCommons

Set of utilities common for timebase projects
Java
5
star
73

eco-commons-avro

Eco Commons Avro
Java
5
star
74

Sitecore-Reference-Storefront-on-Habitat

Sitecore Reference Storefront ported to Sitecore Habitat
C#
5
star
75

atg-build-plugin

Groovy
5
star
76

edp-ddm-architecture

Handlebars
5
star
77

edp-jenkins-operator

This operator creates, deploys, and manages the EDP Jenkins instance on Kubernetes and OpenShift. In addition, the Jenkins instance is equipped with the necessary plugins. There is also the ability to customize the Jenkins instance as well as to check the changes during the application creation
Go
5
star
78

covid-resistance-back-end

COVID Resistance – Back-End
C#
5
star
79

eco-commons-kafka

Eco Commons Kafka
Java
5
star
80

openvasp-java-client

A reference implementation for a JAVA client for the OpenVASP standard. Not yet compatible with the current OpenVASP protocol version.
Java
5
star
81

edp-ddm-notification-service

Java
4
star
82

edp-gerrit-operator

This operator installs and manages Gerrit EDP Component in order to use it as GitProvider and store codebases code
Go
4
star
83

grid-engine-api

Java
4
star
84

osci-working-group

This is the main OSCI community repository. Here we post meeting notes from working group's sessions, and other community-related documentation.
4
star
85

HdDateTime

Date & Time Classes for Java & .NET having nanosecond precision, mostly match the functionality of .NET DateTime/TimeSpan, but have no timezone support and greater performance.
C#
4
star
86

TimeBaseGrafanaPlugin

TimeBase datasource for Grafana
TypeScript
4
star
87

TimeBaseClientPython

Python client samples for TimeBase
Python
4
star
88

openvasp-java-host

A reference implementation for a JAVA host for the OpenVASP standard. Not yet compatible with the current OpenVASP protocol version.
Java
4
star
89

ThreadAffinity

A Java wrapper over net.openhft:affinity providing handy classes to create threads pinned to the specified CPUs.
Java
3
star
90

indigo-node

NodeJS bindings for Indigo Universal Cheminformatics Toolkit
JavaScript
3
star
91

eco-commons

Eco Commons
Java
3
star
92

edp-ddm-excerpt-service-api

Java
3
star
93

edp-architecture

This repository contains the general architecture of EPAM Delivery Platform
3
star
94

deps-fe-usePolling

TypeScript
3
star
95

edp-codebase-operator

This operator prepares codebase repositories in order to use them in CI/CD process
Go
3
star
96

edp-library-stages

A Jenkins shared-library for the reference EDP stages
Groovy
3
star
97

Lagerta

Lagerta is an open source transactional data transport. It supports light snapshots creation and management for in-memory data grids and fabrics.
Java
3
star
98

azurelz

HCL
3
star
99

quanthub-portal

Quanthub Portal Drupal Profile
PHP
3
star
100

syndicate-rule-engine

Python
3
star