Skip to content

Commit

Permalink
Version 0.2.3
Browse files Browse the repository at this point in the history
  • Loading branch information
Diefferson Santos committed May 14, 2019
1 parent 7954152 commit a1a1526
Show file tree
Hide file tree
Showing 16 changed files with 148 additions and 59 deletions.
25 changes: 0 additions & 25 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/encodings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: "kotlin-kapt"

android {
compileSdkVersion 28
Expand All @@ -22,10 +23,15 @@ android {

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "androidx.appcompat:appcompat:1.1.0-alpha05"
implementation "androidx.constraintlayout:constraintlayout:1.1.3"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.26.1-eap13"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.26.1-eap13"
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

implementation project(":library")
}
20 changes: 11 additions & 9 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.coroutines.cache">
package="io.coroutines.cache">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Main2Activity">
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.MAIN"/>

<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/io/coroutines/cache/Main2Activity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.coroutines.cache

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class Main2Activity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
}
}
12 changes: 8 additions & 4 deletions app/src/main/java/io/coroutines/cache/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package io.coroutines.cache

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import androidx.appcompat.app.AppCompatActivity
import io.coroutines.cache.core.CachePolicy
import io.coroutines.cache.core.CoroutinesCache
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import kotlinx.coroutines.android.Main
import java.util.concurrent.TimeUnit
import kotlin.coroutines.CoroutineContext

class MainActivity : AppCompatActivity(), CoroutineScope {
Expand All @@ -25,13 +24,18 @@ class MainActivity : AppCompatActivity(), CoroutineScope {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

launch {
delay(3000)
val myAsyncTet = coroutinesCache.asyncCache({ async { "My Async text!" } }, "Key", CachePolicy.LifeCache(10, TimeUnit.SECONDS)).await()
val myAsyncTet = coroutinesCache.asyncCache({ async { "My Async text!" } }, "Key",CachePolicy.LifecycleCache).await()

withContext(Dispatchers.Main){
text.text = myAsyncTet
}
}

text.setOnClickListener {
startActivity(Intent(this, Main2Activity::class.java))
}
}
}
4 changes: 2 additions & 2 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
Expand All @@ -16,4 +16,4 @@
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
20 changes: 20 additions & 0 deletions app/src/main/res/layout/activity_main2.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="loading..."
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
5 changes: 3 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
ext.kotlin_version = '1.3.0'
ext.kotlin_version = '1.3.21'
ext.lifecycle_version = "2.0.0"
repositories {
maven { url "https://dl.bintray.com/kotlin/kotlin-eap" }
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.android.tools.build:gradle:3.4.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "io.realm:realm-gradle-plugin:5.0.0"
// NOTE: Do not place your application dependencies here; they belong
Expand Down
2 changes: 2 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ org.gradle.jvmargs=-Xmx1536m
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.enableJetifier=true
android.useAndroidX=true
3 changes: 2 additions & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#Tue May 14 10:44:00 BRT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
8 changes: 6 additions & 2 deletions library/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ apply plugin: 'realm-android'


group = 'com.github.diefferson'
version='0.2.2'
version='0.2.3'

android {
compileSdkVersion 28
Expand All @@ -29,6 +29,10 @@ android {

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.26.1-eap13"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
implementation 'com.google.code.gson:gson:2.8.5'
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ import java.util.concurrent.TimeUnit

sealed class CachePolicy{
data class EvictProvider(val fromSource:Boolean) :CachePolicy()
data class LifeCache(val duration: Int, val timeUnit: TimeUnit):CachePolicy()
data class TimeCache(val duration: Int, val timeUnit: TimeUnit):CachePolicy()
object LifecycleCache:CachePolicy()
}
50 changes: 42 additions & 8 deletions library/src/main/java/io/coroutines/cache/core/CoroutinesCache.kt
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package io.coroutines.cache.core

import android.content.Context
import android.util.Log
import androidx.lifecycle.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import io.coroutines.cache.dao.Cache
import io.coroutines.cache.dao.RealmDatabase
import kotlinx.coroutines.*
import java.lang.IllegalStateException
import java.util.*
import kotlin.collections.HashMap
import kotlin.coroutines.CoroutineContext

open class CoroutinesCache(private var context: Context, val test: Boolean = false):CoroutineScope{
open class CoroutinesCache(private var context: Context, val test: Boolean = false, val lifecycleOwner: LifecycleOwner? = null):CoroutineScope{

private val executionJob: Job by lazy { Job() }

Expand All @@ -23,19 +27,37 @@ open class CoroutinesCache(private var context: Context, val test: Boolean = fal
}
}

init {
lifecycleOwner?.lifecycle?.addObserver(object:LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun destroy() {
database.deleteLifecycle()
}
})
}

fun clear() {
database.clear()
}

fun deleteItem(key:String){
database.deleteItem(key)
}


inline fun <reified T:Any> asyncCache(noinline source: suspend ()->Deferred<T>, key: String, cachePolicy: CachePolicy): Deferred<T> {
return if(test){
async{source().await()}
}else{
when(cachePolicy){

is CachePolicy.LifeCache-> cacheLifeResolver( source, key, cachePolicy)
is CachePolicy.TimeCache-> cacheTimeResolver( source, key, cachePolicy)
is CachePolicy.EvictProvider -> cacheProviderResolver(source, key, cachePolicy)
is CachePolicy.LifecycleCache -> cacheLifecycleResolver(source, key)
}
}
}

@PublishedApi internal inline fun <reified T : Any> cacheLifeResolver(noinline source: suspend () -> Deferred<T>, key: String, cachePolicy: CachePolicy.LifeCache): Deferred<T> {
@PublishedApi internal inline fun <reified T : Any> cacheTimeResolver(noinline source: suspend () -> Deferred<T>, key: String, cachePolicy: CachePolicy.TimeCache): Deferred<T> {
getFromCacheValidateTime<T>(key, cachePolicy)?.let {
return async { it }
} ?: run {
Expand All @@ -55,12 +77,24 @@ open class CoroutinesCache(private var context: Context, val test: Boolean = fal
}
}

@PublishedApi internal fun <T> getFromSource(source: suspend ()->Deferred<T>, key: String):Deferred<T>{
@PublishedApi internal inline fun <reified T : Any> cacheLifecycleResolver(noinline source: suspend () -> Deferred<T>, key: String): Deferred<T> {
if(lifecycleOwner == null){
throw IllegalStateException("Necessary pass a lifecycleowner to Coroutines Cache Constructor")
}

return getFromCache<T>(key)?.let {
async { it }
}?:run{
getFromSource(source, key, true)
}
}

@PublishedApi internal fun <T> getFromSource(source: suspend ()->Deferred<T>, key: String, isLifecycle: Boolean = false):Deferred<T>{
return async {
val result = source().await()
database.getDatabase().apply {
beginTransaction()
copyToRealmOrUpdate(Cache(key, Gson().toJson(result), Calendar.getInstance().time))
copyToRealmOrUpdate(Cache(key, Gson().toJson(result), Calendar.getInstance().time, isLifecycle))
commitTransaction()
close()
}
Expand All @@ -78,10 +112,10 @@ open class CoroutinesCache(private var context: Context, val test: Boolean = fal
}
}

@PublishedApi internal inline fun <reified T:Any> getFromCacheValidateTime(key: String, lifeCache: CachePolicy.LifeCache): T? {
@PublishedApi internal inline fun <reified T:Any> getFromCacheValidateTime(key: String, timeCache: CachePolicy.TimeCache): T? {
val resultDb = database.getDatabase().where(Cache::class.java).equalTo("id", key).findFirst()
return if (resultDb != null) {
if(resultDb.date.isValidCache(lifeCache.duration, lifeCache.timeUnit)){
if(resultDb.date.isValidCache(timeCache.duration, timeCache.timeUnit)){
val listType = object : TypeToken<T>() {}.type
Gson().fromJson(resultDb.data, listType) as T
}else{
Expand Down
Loading

0 comments on commit a1a1526

Please sign in to comment.