├── tests ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ └── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── pacoworks │ │ │ │ └── rxobservablediskcache │ │ │ │ └── MainActivity.java │ │ └── AndroidManifest.xml │ └── androidTest │ │ └── java │ │ └── com │ │ └── pacoworks │ │ └── rxobservablediskcache │ │ ├── MyPolicy.java │ │ └── RxObservableDiskCacheTest.java ├── proguard-rules.pro └── build.gradle ├── library ├── .gitignore ├── proguard-rules.pro ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── com │ │ └── pacoworks │ │ └── rxobservablediskcache │ │ ├── Logging.java │ │ ├── Cached.java │ │ ├── policy │ │ ├── VersionPolicy.java │ │ ├── TimePolicy.java │ │ └── TimeAndVersionPolicy.java │ │ └── RxObservableDiskCache.java └── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── settings.gradle ├── LICENSE.md ├── gradle.properties ├── gradlew.bat ├── gradlew └── README.md /tests/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pakoito/RxObservableDiskCache/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /tests/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pakoito/RxObservableDiskCache/HEAD/tests/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /tests/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pakoito/RxObservableDiskCache/HEAD/tests/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /tests/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pakoito/RxObservableDiskCache/HEAD/tests/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /tests/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pakoito/RxObservableDiskCache/HEAD/tests/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /tests/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pakoito/RxObservableDiskCache/HEAD/tests/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | /.idea/copyright 7 | .DS_Store 8 | /build 9 | /captures 10 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | include ':tests', ':library' 18 | -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/francisco.estevez/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /tests/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/francisco.estevez/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /tests/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | RxObservableDiskCache 19 | 20 | -------------------------------------------------------------------------------- /tests/src/androidTest/java/com/pacoworks/rxobservablediskcache/MyPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache; 18 | 19 | public class MyPolicy { 20 | } 21 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License, Version 2.0 2 | =========================== 3 | 4 | Copyright 2016 pakoito 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License.n writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) pakoito 2016 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | #Thu Nov 03 11:59:04 GMT 2016 18 | distributionBase=GRADLE_USER_HOME 19 | distributionPath=wrapper/dists 20 | zipStoreBase=GRADLE_USER_HOME 21 | zipStorePath=wrapper/dists 22 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 23 | -------------------------------------------------------------------------------- /tests/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | #3F51B5 19 | #303F9F 20 | #FF4081 21 | 22 | -------------------------------------------------------------------------------- /tests/src/main/java/com/pacoworks/rxobservablediskcache/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache; 18 | 19 | import android.os.Bundle; 20 | import android.support.v7.app.AppCompatActivity; 21 | 22 | public class MainActivity extends AppCompatActivity { 23 | @Override 24 | protected void onCreate(Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /tests/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.library' 18 | 19 | sourceCompatibility = 1.6 20 | targetCompatibility = 1.6 21 | 22 | android { 23 | compileSdkVersion 25 24 | buildToolsVersion "25.0.0" 25 | 26 | defaultConfig { 27 | minSdkVersion 16 28 | targetSdkVersion 25 29 | versionCode 1 30 | versionName "1.0.0" 31 | } 32 | buildTypes { 33 | release { 34 | minifyEnabled false 35 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 36 | } 37 | } 38 | } 39 | 40 | dependencies { 41 | compile 'com.github.pakoito:RxPaper:2.0.0' 42 | } 43 | -------------------------------------------------------------------------------- /tests/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 19 | 20 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) pakoito 2016 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | # Project-wide Gradle settings. 18 | 19 | # IDE (e.g. Android Studio) users: 20 | # Gradle settings configured through the IDE *will override* 21 | # any settings specified in this file. 22 | 23 | # For more details on how to configure your build environment visit 24 | # http://www.gradle.org/docs/current/userguide/build_environment.html 25 | 26 | # Specifies the JVM arguments used for the daemon process. 27 | # The setting is particularly useful for tweaking memory settings. 28 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 29 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 30 | 31 | # When configured, Gradle will run in incubating parallel mode. 32 | # This option should only be used with decoupled projects. More details, visit 33 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 34 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /tests/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.application' 18 | 19 | android { 20 | compileSdkVersion 23 21 | buildToolsVersion "23.0.3" 22 | 23 | defaultConfig { 24 | applicationId "com.pacoworks.rxobservablediskcache.sample" 25 | minSdkVersion 16 26 | targetSdkVersion 23 27 | versionCode 1 28 | versionName "1.0.0" 29 | testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' 30 | } 31 | buildTypes { 32 | release { 33 | minifyEnabled false 34 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 35 | } 36 | } 37 | } 38 | 39 | dependencies { 40 | compile 'com.android.support:appcompat-v7:23.1.1' 41 | testCompile 'junit:junit:4.12' 42 | androidTestCompile "com.android.support.test:runner:0.5" 43 | androidTestCompile "com.android.support.test:rules:0.5" 44 | compile project(':library') 45 | } 46 | -------------------------------------------------------------------------------- /library/src/main/java/com/pacoworks/rxobservablediskcache/Logging.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache; 18 | 19 | import android.util.Log; 20 | 21 | import java.util.Locale; 22 | 23 | import rx.functions.Action0; 24 | import rx.functions.Action1; 25 | 26 | /** 27 | * Private class containing logging methods for {@link RxObservableDiskCache} 28 | * 29 | * @author pakoito 30 | */ 31 | class Logging { 32 | private static final String TAG = "RxObservableDiskCache"; 33 | 34 | private Logging() { 35 | // No instances 36 | } 37 | 38 | static Action1> logCacheHit(final String key) { 39 | return new Action1>() { 40 | @Override 41 | public void call(Cached valuePolicyCached) { 42 | Log.d(TAG, "Cache hit: " + key); 43 | } 44 | }; 45 | } 46 | 47 | static Action1 logCacheMiss(final String key) { 48 | return new Action1() { 49 | @Override 50 | public void call(Throwable t) { 51 | Log.e(TAG, 52 | String.format(Locale.US, "Cache miss: %s%nCaused by: %s", key, 53 | t.getMessage())); 54 | } 55 | }; 56 | } 57 | 58 | static Action0 logCacheInvalid(final String key) { 59 | return new Action0() { 60 | @Override 61 | public void call() { 62 | Log.d(TAG, "Cache invalid: " + key); 63 | } 64 | }; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /library/src/main/java/com/pacoworks/rxobservablediskcache/Cached.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache; 18 | 19 | /** 20 | * Wrapper object for results of {@link RxObservableDiskCache} methods 21 | * 22 | * @param type of the data to store 23 | * @param type of the policy to store 24 | * @author pakoito 25 | */ 26 | public class Cached { 27 | public final Value value; 28 | 29 | public final Policy policy; 30 | 31 | public final boolean isFromDisk; 32 | 33 | Cached(Value value, Policy policy, boolean isFromDisk) { 34 | this.value = value; 35 | this.policy = policy; 36 | this.isFromDisk = isFromDisk; 37 | } 38 | 39 | @Override 40 | public boolean equals(Object o) { 41 | if (this == o) 42 | return true; 43 | if (o == null || getClass() != o.getClass()) 44 | return false; 45 | Cached cached = (Cached)o; 46 | if (isFromDisk != cached.isFromDisk) { 47 | return false; 48 | } 49 | if (!value.equals(cached.value)) { 50 | return false; 51 | } 52 | return policy.equals(cached.policy); 53 | } 54 | 55 | @Override 56 | public int hashCode() { 57 | int result = value.hashCode(); 58 | result = 31 * result + policy.hashCode(); 59 | result = 31 * result + (isFromDisk ? 1 : 0); 60 | return result; 61 | } 62 | 63 | @Override 64 | public String toString() { 65 | return "Cached{" + "isFromDisk=" + isFromDisk + ", policy=" + policy + ", value=" + value 66 | + '}'; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /library/src/main/java/com/pacoworks/rxobservablediskcache/policy/VersionPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache.policy; 18 | 19 | import com.pacoworks.rxobservablediskcache.RxObservableDiskCache; 20 | 21 | import rx.functions.Func1; 22 | 23 | /** 24 | * Policy class using versioning for invalidation. 25 | *

26 | * It checks whether the version of the Value matches the expected one. 27 | * 28 | * @author pakoito 29 | */ 30 | public class VersionPolicy { 31 | public final int version; 32 | 33 | VersionPolicy(int version) { 34 | this.version = version; 35 | } 36 | 37 | /** 38 | * Creation function to pass to {@link RxObservableDiskCache} 39 | * 40 | * @param version version of the Value 41 | * @return creation function 42 | */ 43 | public static Func1 create(final int version) { 44 | return new Func1() { 45 | @Override 46 | public VersionPolicy call(T t) { 47 | return new VersionPolicy(version); 48 | } 49 | }; 50 | } 51 | 52 | /** 53 | * Validation function to pass to {@link RxObservableDiskCache} 54 | * 55 | * @param expectedVersion expected version to pass validation 56 | * @return validation function 57 | */ 58 | public static Func1 validate(final int expectedVersion) { 59 | return new Func1() { 60 | @Override 61 | public Boolean call(VersionPolicy myPolicy) { 62 | return myPolicy.version == expectedVersion; 63 | } 64 | }; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /library/src/main/java/com/pacoworks/rxobservablediskcache/policy/TimePolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache.policy; 18 | 19 | import com.pacoworks.rxobservablediskcache.RxObservableDiskCache; 20 | 21 | import rx.functions.Func1; 22 | 23 | /** 24 | * Policy class using timestamping for invalidation. 25 | *

26 | * It checks whether the Value has been stored less than a maximum caching time. 27 | * 28 | * @author pakoito 29 | */ 30 | public class TimePolicy { 31 | public final long timestamp; 32 | 33 | TimePolicy() { 34 | timestamp = System.currentTimeMillis(); 35 | } 36 | 37 | TimePolicy(long timestampMillis) { 38 | this.timestamp = timestampMillis; 39 | } 40 | 41 | /** 42 | * Creation function to pass to {@link RxObservableDiskCache} 43 | *

44 | * It uses {@link System#currentTimeMillis()} internally. 45 | * 46 | * @return creation function 47 | */ 48 | public static Func1 create() { 49 | return new Func1() { 50 | @Override 51 | public TimePolicy call(T t) { 52 | return new TimePolicy(); 53 | } 54 | }; 55 | } 56 | 57 | /** 58 | * Creation function to pass to {@link RxObservableDiskCache} 59 | * 60 | * @param timestampMillis timestamp in milliseconds 61 | * @return creation function 62 | */ 63 | public static Func1 create(final long timestampMillis) { 64 | return new Func1() { 65 | @Override 66 | public TimePolicy call(T t) { 67 | return new TimePolicy(timestampMillis); 68 | } 69 | }; 70 | } 71 | 72 | /** 73 | * Validation function to pass to {@link RxObservableDiskCache} 74 | * 75 | * @param maxCacheDurationMillis maximum caching time allowed 76 | * @return validation function 77 | */ 78 | public static Func1 validate(final long maxCacheDurationMillis) { 79 | return new Func1() { 80 | @Override 81 | public Boolean call(TimePolicy myPolicy) { 82 | return System.currentTimeMillis() - myPolicy.timestamp < maxCacheDurationMillis; 83 | } 84 | }; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /library/src/main/java/com/pacoworks/rxobservablediskcache/policy/TimeAndVersionPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache.policy; 18 | 19 | import com.pacoworks.rxobservablediskcache.RxObservableDiskCache; 20 | 21 | import rx.functions.Func1; 22 | 23 | /** 24 | * Policy class using timestamping and versioning for invalidation. 25 | *

26 | * It checks whether the Value has been stored less than a maximum caching time, and that the 27 | * version of the Value matches the expected one. 28 | * 29 | * @author pakoito 30 | */ 31 | public class TimeAndVersionPolicy { 32 | public final long timestamp; 33 | 34 | public final int version; 35 | 36 | TimeAndVersionPolicy(final long timestampMillis, final int version) { 37 | this.timestamp = timestampMillis; 38 | this.version = version; 39 | } 40 | 41 | /** 42 | * Creation function to pass to {@link RxObservableDiskCache} 43 | *

44 | * It uses {@link System#currentTimeMillis()} internally. 45 | * 46 | * @param version version of the Value 47 | * @return creation function 48 | */ 49 | public static Func1 create(final int version) { 50 | return new Func1() { 51 | @Override 52 | public TimeAndVersionPolicy call(T t) { 53 | return new TimeAndVersionPolicy(System.currentTimeMillis(), version); 54 | } 55 | }; 56 | } 57 | 58 | /** 59 | * Creation function to pass to {@link RxObservableDiskCache} 60 | * 61 | * @param timestampMillis timestamp in milliseconds 62 | * @param version version of the Value @return creation function 63 | */ 64 | public static Func1 create(final long timestampMillis, 65 | final int version) { 66 | return new Func1() { 67 | @Override 68 | public TimeAndVersionPolicy call(T t) { 69 | return new TimeAndVersionPolicy(timestampMillis, version); 70 | } 71 | }; 72 | } 73 | 74 | /** 75 | * Validation function to pass to {@link RxObservableDiskCache} 76 | * 77 | * @param maxCacheDurationMillis maximum caching time allowed 78 | * @param expectedVersion expected version to pass validation 79 | * @return validation function 80 | */ 81 | public static Func1 validate(final long maxCacheDurationMillis, 82 | final int expectedVersion) { 83 | return new Func1() { 84 | @Override 85 | public Boolean call(TimeAndVersionPolicy myPolicy) { 86 | final boolean isTimeCorrect = System.currentTimeMillis() - myPolicy.timestamp < maxCacheDurationMillis; 87 | final boolean isVersionCorrect = myPolicy.version == expectedVersion; 88 | return isTimeCorrect && isVersionCorrect; 89 | } 90 | }; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /tests/src/androidTest/java/com/pacoworks/rxobservablediskcache/RxObservableDiskCacheTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache; 18 | 19 | import java.io.Serializable; 20 | import java.util.Arrays; 21 | import java.util.List; 22 | 23 | import org.junit.Assert; 24 | import org.junit.Before; 25 | import org.junit.Rule; 26 | import org.junit.Test; 27 | import org.junit.runner.RunWith; 28 | 29 | import com.pacoworks.rxpaper.RxPaperBook; 30 | 31 | import android.support.test.rule.ActivityTestRule; 32 | import android.support.test.runner.AndroidJUnit4; 33 | 34 | import rx.Single; 35 | import rx.functions.Func1; 36 | import rx.observers.TestSubscriber; 37 | 38 | @RunWith(AndroidJUnit4.class) 39 | public class RxObservableDiskCacheTest { 40 | private static final String KEY = "test_key"; 41 | 42 | @Rule 43 | public final ActivityTestRule activity = new ActivityTestRule<>( 44 | MainActivity.class); 45 | 46 | private RxPaperBook testBook; 47 | 48 | @Before 49 | public void setUp() { 50 | RxPaperBook.init(activity.getActivity()); 51 | testBook = RxPaperBook.with("test_book"); 52 | testBook.destroy().subscribe(); 53 | } 54 | 55 | public TestSubscriber initCache() { 56 | final List initialList = Arrays. asList(true, 1, "hello"); 57 | final TestSubscriber, MyPolicy>> subscriber = TestSubscriber 58 | .create(); 59 | RxObservableDiskCache.transform(Single.just(initialList), KEY, testBook, 60 | new Func1, MyPolicy>() { 61 | @Override 62 | public MyPolicy call(List serializables) { 63 | return new MyPolicy(); 64 | } 65 | }, new Func1() { 66 | @Override 67 | public Boolean call(MyPolicy myPolicy) { 68 | return true; 69 | } 70 | }).subscribe(subscriber); 71 | subscriber.awaitTerminalEvent(); 72 | return subscriber; 73 | } 74 | 75 | @Test 76 | public void emptyCache_cacheFail_getObservable() { 77 | final TestSubscriber subscriber = initCache(); 78 | /* Assert */ 79 | subscriber.assertNoErrors(); 80 | subscriber.assertCompleted(); 81 | subscriber.assertValueCount(1); 82 | } 83 | 84 | @Test 85 | public void emptyCache_observableFails_getException() { 86 | final TestSubscriber> subscriber = TestSubscriber.create(); 87 | /* Act */ 88 | RxObservableDiskCache.transform(Single. error(new IllegalStateException()), KEY, 89 | testBook, new Func1() { 90 | @Override 91 | public MyPolicy call(Integer serializables) { 92 | return new MyPolicy(); 93 | } 94 | }, new Func1() { 95 | @Override 96 | public Boolean call(MyPolicy myPolicy) { 97 | return true; 98 | } 99 | }).subscribe(subscriber); 100 | subscriber.awaitTerminalEvent(); 101 | /* Assert */ 102 | subscriber.assertValueCount(0); 103 | subscriber.assertError(IllegalStateException.class); 104 | } 105 | 106 | @Test 107 | public void validCache_cacheHit_getCacheThenGetObservable() { 108 | initCache(); 109 | final List list = Arrays. asList(true, 1, "hello"); 110 | final TestSubscriber, MyPolicy>> subscriber = TestSubscriber 111 | .create(); 112 | /* Act */ 113 | RxObservableDiskCache.transform(Single.just(list), KEY, testBook, 114 | new Func1, MyPolicy>() { 115 | @Override 116 | public MyPolicy call(List serializables) { 117 | return new MyPolicy(); 118 | } 119 | }, new Func1() { 120 | @Override 121 | public Boolean call(MyPolicy myPolicy) { 122 | return true; 123 | } 124 | }).subscribe(subscriber); 125 | subscriber.awaitTerminalEvent(); 126 | /* Assert */ 127 | subscriber.assertNoErrors(); 128 | subscriber.assertCompleted(); 129 | subscriber.assertValueCount(2); 130 | } 131 | 132 | @Test 133 | public void validCache_cacheMiss_deleteCacheThenGetObservable() { 134 | initCache(); 135 | final List list = Arrays. asList(true, 1, "hello"); 136 | final TestSubscriber, MyPolicy>> subscriber = TestSubscriber 137 | .create(); 138 | /* Act */ 139 | RxObservableDiskCache.transform(Single.just(list), KEY, testBook, 140 | new Func1, MyPolicy>() { 141 | @Override 142 | public MyPolicy call(List serializables) { 143 | return new MyPolicy(); 144 | } 145 | }, new Func1() { 146 | @Override 147 | public Boolean call(MyPolicy myPolicy) { 148 | return false; 149 | } 150 | }).subscribe(subscriber); 151 | subscriber.awaitTerminalEvent(); 152 | /* Assert */ 153 | subscriber.assertNoErrors(); 154 | subscriber.assertCompleted(); 155 | subscriber.assertValueCount(1); 156 | Assert.assertTrue(testBook.exists(KEY).toBlocking().value()); 157 | } 158 | 159 | @Test 160 | public void validCache_cacheHitAndObservableFails_getCacheThenGetException() { 161 | initCache(); 162 | final TestSubscriber> subscriber = TestSubscriber.create(); 163 | RxObservableDiskCache.transform(Single. error(new IllegalStateException()), KEY, 164 | testBook, new Func1() { 165 | @Override 166 | public MyPolicy call(Integer serializables) { 167 | return new MyPolicy(); 168 | } 169 | }, new Func1() { 170 | @Override 171 | public Boolean call(MyPolicy myPolicy) { 172 | return true; 173 | } 174 | }).subscribe(subscriber); 175 | subscriber.awaitTerminalEvent(); 176 | /* Assert */ 177 | subscriber.assertValueCount(1); 178 | subscriber.assertError(IllegalStateException.class); 179 | } 180 | 181 | @Test 182 | public void validCache_cacheMissAndObservableFails_deleteCacheThenGetException() { 183 | initCache(); 184 | final TestSubscriber> subscriber = TestSubscriber.create(); 185 | RxObservableDiskCache.transform(Single. error(new IllegalStateException()), KEY, 186 | testBook, new Func1() { 187 | @Override 188 | public MyPolicy call(Integer serializables) { 189 | return new MyPolicy(); 190 | } 191 | }, new Func1() { 192 | @Override 193 | public Boolean call(MyPolicy myPolicy) { 194 | return false; 195 | } 196 | }).subscribe(subscriber); 197 | subscriber.awaitTerminalEvent(); 198 | /* Assert */ 199 | subscriber.assertValueCount(0); 200 | subscriber.assertError(IllegalStateException.class); 201 | Assert.assertFalse(testBook.exists(KEY).toBlocking().value()); 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RxObservableDiskCache 2 | 3 | RxObservableDiskCache is a library to save the results of `Single`s or single value `Observable`s request on a local disk cache, so the next time the same request is called you get an immediate result. 4 | 5 | For the RxJava 2.X version, please go to [RxObservableDiskCache2](https://github.com/pakoito/RxObservableDiskCache2). 6 | 7 | ## Rationale 8 | 9 | RxObservableDiskCache was created with a single purpose: help you store your network results in a disk cache and refetch them as soon as they're re-requested. It also solves displaying values while waiting for network results, when the user is offline, or when the server is unavailable. 10 | 11 | To provide a good UX your app should be able to work offline and also display results as soon as they're requested. Historically this has been done by storing your data on SQLite, or a custom network cache. These options introduce maintenance overhead: SQLite requires a strict data model, careful database updates, and usage of syntactic sugar libraries like ORMs to make it palatable. The custom network cache depends on your server team introducing etags and other similar mechanisms, which are not always available. 12 | 13 | RxObservableDiskCache relies on a technology that's common on desktop and server: key-value disk stores. By using [RxPaper](https://github.com/pakoito/RxPaper) behind the scenes it's able to efficiently store any result in an schemaless document just to refetch it later. This makes caching transparent for most network calls, you just need to configure them once with the correct caching policy. It's just one method call that wraps your `Single` or single value `Observable`. 14 | 15 | To avoid your data getting stale due to time limits or versioning, RxObservableDiskCache allows you to store an arbitrary caching Policy. This Policy is any simple object that helps you identify whether your data is outdated and has to be removed. RxObservableDiskCache provides three different Policy objects, but you can create and use your own. This way you can decide how to handle staleness the same way you would do in SQLite or when using etags: by dropping the data, or programming defensively to account for model changes. 16 | 17 | ## Updating from 1.X 18 | 19 | As [PaperDb 2.0](https://github.com/pilgr/Paper/releases/tag/2.0) has updated from Kryo 3 to [Kryo 4](https://github.com/EsotericSoftware/kryo/releases/tag/kryo-parent-4.0.0), the internal representation model has changed. PaperDb deals with these changes internally, so the migration should be transparent. If you find any data compatibility bug, please [create a ticket](https://github.com/pilgr/Paper/issues/new). 20 | 21 | ## Usage 22 | 23 | #### Storage 24 | 25 | RxObservableDiskCache uses [RxPaper](https://github.com/pakoito/RxPaper) internally, so it's recommended to go to its [README](https://github.com/pakoito/RxPaper/blob/master/README.md) for reference on what Values are serializable, and what other behaviours are expected. RxObservableDiskCache is not opinionanted about the `RxPaperBook` you pass onto it, so feel free to use it externally to read, modify, or purge any data outside the RxObservableDiskCache scope. 26 | 27 | #### Policy 28 | 29 | Behind the scenes Policy objects are stored and retrieved separately from Values to avoid unnecessary deserialization. They're checked before the Value is retrieved to see if it has to be deleted instead. Policy objects are recommended to be kept as small as possible. 30 | 31 | Three simple Policy classes are included with RxObservableDiskCache: TimePolicy, VersionPolicy, and TimeAndVersionPolicy. You can still use any other class as Policy. 32 | 33 | #### Error handling 34 | 35 | Any storage errors are: logged with a "cache miss" message, the current key and value get deleted, and the error is forwarded. 36 | 37 | Any errors on the operation are forwarded too, like with any `Observable`. 38 | 39 | Expect 0 results for cache and operation failures, 1 result when the cache is not found or valid and the operation succeeds, 1 result when the cache is found and valid but the operation fails, and 2 results when both the cache and the operation succeed. 40 | 41 | There is a full test suite with examples on the sample project. 42 | 43 | #### Configuration 44 | 45 | The configuration parameters are: 46 | 47 | * The `Single` or single value `Observable` operation to be wrapped. 48 | * A key string under which the Value will be stored. 49 | * The [RxPaperBook](https://github.com/pakoito/RxPaper/blob/master/README.md#working-on-a-book) database where the Value and Policy will be stored. 50 | * A creation and validation functions for the Policy. 51 | 52 | #### Static single use 53 | 54 | `RxObservableDiskCache.transform()` are a set of methods you can call with any observable and configuration parameters that will return the transformed `Observable`. 55 | 56 | ```java 57 | RxObservableDiskCache. 58 | transform( 59 | userRequest(), 60 | "user_profile", 61 | RxPaperBook.with("my_app_cache"), 62 | TimeAndVersionPolicy.create(BuildConfig.VERSION_CODE), 63 | TimeAndVersionPolicy.validate(BuildConfig.VERSION_CODE)) 64 | .subscribe(/* Do something withe the data */); 65 | ``` 66 | #### Instance 67 | 68 | `RxObservableDiskCache.create()` creates an instance of RxObservableDiskCache for the same book, Value and Policy that can be reused for different `Single`s or single value `Observable`s. 69 | 70 | ```java 71 | RxObservableDiskCache myCache = 72 | RxObservableDiskCache.create( 73 | RxPaperBook.with("my_app_cache"), 74 | TimeAndVersionPolicy.create(BuildConfig.VERSION_CODE), 75 | TimeAndVersionPolicy.validate(BuildConfig.VERSION_CODE)); 76 | 77 | myCache.transform(userRequest(), "user_profile").subscribe(/* Do something withe the data */); 78 | 79 | myCache.transform(userRequest("54663"), "friend_54663_profile").subscribe(/* Do something withe the data */); 80 | ``` 81 | 82 | ## Distribution 83 | 84 | Add as a dependency to your `build.gradle` 85 | ```groovy 86 | repositories { 87 | ... 88 | maven { url "https://jitpack.io" } 89 | ... 90 | } 91 | 92 | dependencies { 93 | ... 94 | compile 'com.github.pakoito:RxObservableDiskCache:2.0.0' 95 | ... 96 | } 97 | ``` 98 | or to your `pom.xml` 99 | ```xml 100 | 101 | 102 | jitpack.io 103 | https://jitpack.io 104 | 105 | 106 | 107 | 108 | com.github.pakoito 109 | RxObservableDiskCache 110 | 2.0.0 111 | 112 | ``` 113 | 114 | ## FAQ 115 | 116 | #### How fast is it? Isn't there an overhead to be always getting old values? 117 | 118 | As fast as the underlying [Paper](https://github.com/pilgr/Paper) library. Policy is used to reduce deserialization overhead when it's not required, so Values are only fetched when they're surely required and validated. [Kryo](https://github.com/EsotericSoftware/kryo) is binary serialization faster than Jackson and Gson. 119 | 120 | #### How do I deal with model updates? 121 | 122 | Same way you do on SQLite: you drop the data or code defensively. The storage is schemaless, so no update scripts are required. The data is deserialized under the same premises as [Paper](https://github.com/pilgr/Paper)/[Kryo](https://github.com/EsotericSoftware/kryo), so their documentation is the best reference. The usage of Policy was introduced to automate the process, but you're free to ignore it and operate directly on the [RxPaperBook](https://github.com/pakoito/RxPaper/blob/master/README.md#working-on-a-book) you pass to the transformation. 123 | 124 | #### Why isn't it an `Observable` transformer instead? 125 | 126 | Because it transforms from `Single` to `Observable`, and I wanted to keep the transformation explicit. 127 | 128 | #### I want to store an `Observable` that returns more than one result 129 | 130 | Although it doesn't make much sense to me to duplicate every value on an `Observable` operation, you can do it like this: 131 | 132 | ```java 133 | myNotSingleObservable.flatMap( 134 | value -> 135 | RxObservableDiskCache.transform( 136 | Single.just(value), /* rest of parameters */)) 137 | ``` 138 | 139 | #### If I cancel an operation it throws a `Single` or `Completable` incomplete exception 140 | 141 | Database operations are not meant to be cancellable, and shouldn't be applied directly to UI precisely to avoid leaks. Apply them to a `PublishSubject` instead, and bind that subject directly to the view making sure that you `unsubscribe()` it when required. 142 | 143 | ## Contribution 144 | 145 | PRs and suggestions for new features welcome. 146 | 147 | For any error report please send an issue with a full stack trace and reproduction steps. 148 | 149 | ## License 150 | 151 | Copyright (c) pakoito 2016 152 | 153 | The Apache Software License, Version 2.0 154 | 155 | See LICENSE.md 156 | -------------------------------------------------------------------------------- /library/src/main/java/com/pacoworks/rxobservablediskcache/RxObservableDiskCache.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) pakoito 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.pacoworks.rxobservablediskcache; 18 | 19 | import android.content.Context; 20 | 21 | import com.pacoworks.rxpaper.RxPaperBook; 22 | 23 | import rx.Completable; 24 | import rx.Observable; 25 | import rx.Single; 26 | import rx.functions.Func1; 27 | 28 | /** 29 | * Static methods to add disk caching behaviour to {@link Single} objects. 30 | *

31 | * Make sure to call {@link RxPaperBook#init(Context)} at least once beforehand to initialize the 32 | * underlying database. 33 | * 34 | * @param type of the data to store 35 | * @param

type of the policy to store 36 | * @author pakoito 37 | */ 38 | public class RxObservableDiskCache { 39 | private static final String POLICY_APPEND = "_policy"; 40 | 41 | private final RxPaperBook book; 42 | 43 | private final Func1 policyCreator; 44 | 45 | private final Func1 policyValidator; 46 | 47 | RxObservableDiskCache(RxPaperBook book, Func1 policyCreator, 48 | Func1 policyValidator) { 49 | this.book = book; 50 | this.policyValidator = policyValidator; 51 | this.policyCreator = policyCreator; 52 | } 53 | 54 | /** 55 | * Creates a reusable {@link RxObservableDiskCache} for the same {@link RxPaperBook}, Policy and 56 | * Value types. 57 | * 58 | * @param book {@link RxPaperBook} storage book 59 | * @param policyCreator lazy method to construct a Policy object 60 | * @param policyValidator lazy method to validate a Policy object 61 | */ 62 | public static RxObservableDiskCache create( 63 | RxPaperBook book, Func1 policyCreator, Func1 policyValidator) { 64 | return new RxObservableDiskCache<>(book, policyCreator, policyValidator); 65 | } 66 | 67 | /** 68 | * Transforms a {@link Single} into an {@link Observable} returning a disk cached version of the 69 | * latest Value seen for the same key followed by the {@link Single} result. 70 | *

71 | * The execution assures that the cached Value, if available, will be returned first. If no 72 | * Value is cached, or its Policy is not validated, then the current Value and Policy are 73 | * deleted silently and just the value of the {@link Single} is returned. 74 | *

75 | * This version uses a default {@link RxPaperBook}. 76 | * 77 | * @param single {@link Single} operation whose result is to be cached 78 | * @param key string value under where the values will be stored 79 | * @param policyCreator lazy method to construct a Policy object 80 | * @param policyValidator lazy method to validate a Policy object 81 | * @param type of the data to store 82 | * @param

type of the policy to store 83 | * @return an {@link Observable} that will return a cached Value followed by the result of 84 | * executing single 85 | */ 86 | public static Observable> transform( 87 | Single single, String key, Func1 policyCreator, Func1 policyValidator) { 88 | return transform(single, key, RxPaperBook.with(BuildConfig.APPLICATION_ID), policyCreator, 89 | policyValidator); 90 | } 91 | 92 | /** 93 | * Transforms a {@link Single} into an {@link Observable} returning a disk cached version of the 94 | * latest Value seen for the same key followed by the {@link Single} result. 95 | *

96 | * The execution assures that the cached Value, if available, will be returned first. If no 97 | * Value is cached, or its Policy is not validated, then the current Value and Policy are 98 | * deleted silently and just the value of the {@link Single} is returned. 99 | * 100 | * @param single {@link Single} operation whose result is to be cached 101 | * @param key string value under where the values will be stored 102 | * @param paperBook storage book 103 | * @param policyCreator lazy method to construct a Policy object 104 | * @param policyValidator lazy method to validate a Policy object 105 | * @param type of the data to store 106 | * @param

type of the policy to store 107 | * @return an {@link Observable} that will return a cached Value followed by the result of 108 | * executing single 109 | */ 110 | public static Observable> transform( 111 | final Single single, final String key, final RxPaperBook paperBook, 112 | final Func1 policyCreator, final Func1 policyValidator) { 113 | return Observable 114 | /* Errors require being delayed so the cached subscription is completed even if the remote one fails */ 115 | .concatDelayError( 116 | RxObservableDiskCache.requestCachedValue(key, paperBook, policyValidator), 117 | RxObservableDiskCache.requestFreshValue(single, key, paperBook, policyCreator)); 118 | } 119 | 120 | private static Observable> requestCachedValue( 121 | final String key, final RxPaperBook cache, Func1 policyValidator) { 122 | return cache 123 | .

read(composePolicyKey(key)) 124 | .toObservable() 125 | .filter(policyValidator) 126 | .switchIfEmpty( 127 | RxObservableDiskCache.

deleteValueAndPolicy(key, cache) 128 | .doOnCompleted(Logging.logCacheInvalid(key))) 129 | .flatMap(RxObservableDiskCache. readValue(key, cache)) 130 | .doOnNext(Logging. logCacheHit(key)) 131 | .doOnError(Logging. logCacheMiss(key)) 132 | .onErrorResumeNext(RxObservableDiskCache. handleErrors(key, cache)); 133 | } 134 | 135 | private static

Observable

deleteValueAndPolicy(String key, RxPaperBook cache) { 136 | return Completable.mergeDelayError(cache.delete(key), cache.delete(composePolicyKey(key))) 137 | .toObservable(); 138 | } 139 | 140 | private static Func1>> readValue( 141 | final String key, final RxPaperBook cache) { 142 | return new Func1>>() { 143 | @Override 144 | public Observable> call(final P policy) { 145 | return cache. read(key) 146 | .map(RxObservableDiskCache. createDiskCached(policy)) 147 | .toObservable(); 148 | } 149 | }; 150 | } 151 | 152 | private static Func1>> handleErrors( 153 | final String key, final RxPaperBook cache) { 154 | return new Func1>>() { 155 | @Override 156 | public Observable> call(final Throwable throwable) { 157 | return RxObservableDiskCache.> deleteValueAndPolicy(key, cache) 158 | .flatMap( 159 | new Func1, Observable>>() { 160 | @Override 161 | public Observable> call( 162 | Cached valuePolicyCached) { 163 | return Observable.error(throwable); 164 | } 165 | }); 166 | } 167 | }; 168 | } 169 | 170 | private static Observable> requestFreshValue( 171 | Single single, String key, RxPaperBook cache, Func1 policyCreator) { 172 | return single.toObservable() 173 | .map(createObservableCached(policyCreator)) 174 | .flatMap(RxObservableDiskCache. toStoreKeyAndValue(key, cache)); 175 | } 176 | 177 | private static Func1, Observable>> toStoreKeyAndValue( 178 | final String key, final RxPaperBook cache) { 179 | return new Func1, Observable>>() { 180 | @Override 181 | public Observable> call(final Cached ktCached) { 182 | return Completable 183 | .mergeDelayError( 184 | cache.write(key, ktCached.value), 185 | cache.write(composePolicyKey(key), ktCached.policy)) 186 | .andThen(Observable.just(ktCached)); 187 | } 188 | }; 189 | } 190 | 191 | private static String composePolicyKey(String key) { 192 | return key + POLICY_APPEND; 193 | } 194 | 195 | private static Func1> createDiskCached( 196 | final P policy) { 197 | return new Func1>() { 198 | @Override 199 | public Cached call(V value) { 200 | return new Cached<>(value, policy, true); 201 | } 202 | }; 203 | } 204 | 205 | private static Func1> createObservableCached( 206 | final Func1 policyCreator) { 207 | return new Func1>() { 208 | @Override 209 | public Cached call(V value) { 210 | return new Cached<>(value, policyCreator.call(value), false); 211 | } 212 | }; 213 | } 214 | 215 | /** 216 | * Transforms a {@link Single} into an {@link Observable} returning a disk cached version of the 217 | * latest Value seen for the same key followed by the {@link Single} result. 218 | *

219 | * The execution assures that the cached Value, if available, will be returned first. If no 220 | * Value is cached, or its Policy is not validated, then the current Value and Policy are 221 | * deleted silently and just the value of the {@link Single} is returned. 222 | * 223 | * @param single {@link Single} operation whose result is to be cached 224 | * @param key string value under where the values will be stored 225 | * @return an {@link Observable} that will return a cached Value followed by the result of 226 | * executing single 227 | */ 228 | public Observable> transform(Single single, String key) { 229 | return transform(single, key, book, policyCreator, policyValidator); 230 | } 231 | } 232 | --------------------------------------------------------------------------------