├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── rxcache-kotlin
├── build.gradle
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── zchu
│ └── rxcache
│ └── kotlin
│ └── RxCache.kt
├── rxcache
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── zchu
│ └── rxcache
│ ├── CacheCore.java
│ ├── CacheHolder.java
│ ├── CacheTarget.java
│ ├── LruDiskCache.java
│ ├── LruMemoryCache.java
│ ├── RxCache.java
│ ├── RxCacheHelper.java
│ ├── data
│ ├── CacheResult.java
│ └── ResultFrom.java
│ ├── diskconverter
│ ├── GsonDiskConverter.java
│ ├── IDiskConverter.java
│ └── SerializableDiskConverter.java
│ ├── stategy
│ ├── CacheAndRemoteStrategy.java
│ ├── CacheStrategy.java
│ ├── FirstCacheStrategy.java
│ ├── FirstCacheTimeoutStrategy.java
│ ├── FirstRemoteStrategy.java
│ ├── IFlowableStrategy.java
│ ├── IObservableStrategy.java
│ ├── IStrategy.java
│ ├── NoneStrategy.java
│ ├── OnlyCacheStrategy.java
│ └── OnlyRemoteStrategy.java
│ └── utils
│ ├── LogUtils.java
│ ├── MemorySizeOf.java
│ ├── Occupy.java
│ └── Utils.java
├── sample-debug.apk
├── sample
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── zchu
│ │ └── sample
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── zchu
│ │ │ └── sample
│ │ │ ├── MainActivity.kt
│ │ │ ├── Movie.kt
│ │ │ └── ServerAPI.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── 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-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── zchu
│ └── sample
│ └── ExampleUnitTest.java
├── screenshots
├── s0.gif
└── s1.gif
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 |
3 |
4 | # Files for the ART/Dalvik VM
5 | *.dex
6 |
7 | # Java class files
8 | *.class
9 |
10 | # Generated files
11 | bin/
12 | gen/
13 | out/
14 |
15 | # Gradle files
16 | .gradle/
17 | .idea/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # Intellij
36 | *.iml
37 | .idea/workspace.xml
38 |
39 | # Keystore files
40 | *.jks
41 | ### Android template
42 | # Built application files
43 |
44 |
45 | # Files for the ART/Dalvik VM
46 | *.dex
47 |
48 | # Java class files
49 | *.class
50 |
51 | # Generated files
52 | bin/
53 | gen/
54 | out/
55 |
56 | # Gradle files
57 | .gradle/
58 | build/
59 |
60 | # Local configuration file (sdk path, etc)
61 | local.properties
62 |
63 | # Proguard folder generated by Eclipse
64 | proguard/
65 |
66 | # Log Files
67 | *.log
68 |
69 | # Android Studio Navigation editor temp files
70 | .navigation/
71 |
72 | # Android Studio captures folder
73 | captures/
74 |
75 | # Intellij
76 | *.iml
77 | .idea/workspace.xml
78 |
79 | # Keystore files
80 | *.jks
81 |
82 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RxCache
2 |
3 | [  ](https://bintray.com/zchu/maven/rxcache/_latestVersion)
4 |
5 |
6 |
7 |
8 | 简单一步,缓存搞定。这是一个专用于 RxJava,解决 Android 中对任何 Observable 发出的结果做缓存处理的框架。
9 |
10 | 
11 |
12 | [下载APK](https://raw.githubusercontent.com/z-chu/RxCache/master/sample-debug.apk)
13 |
14 | ## 特性
15 | ### 缓存层级
16 |
17 | * Observable
18 | * 内存缓存 - LruCache
19 | * 磁盘缓存 - DiskLruCache
20 |
21 |
22 | ### 目前已有的存储策略
23 |
24 | * 优先网络
25 | * 优先缓存
26 | * 优先缓存,并设置超时时间
27 | * 仅加载网络,但数据依然会被缓存
28 | * 先加载缓存,后加载网络
29 | * 仅加载网络,不缓存
30 |
31 |
32 |
33 | ## Getting started
34 | ### Add the dependencies
35 | ```groovy
36 | allprojects {
37 | repositories {
38 | maven { url 'https://jitpack.io' }
39 | }
40 | }
41 | ```
42 | **RxJava 2.0**
43 | ```groovy
44 | implementation 'com.github.z-chu.RxCache:rxcache:2.3.5'
45 | ```
46 |
47 | **RxJava 3.0**
48 | ```groovy
49 | implementation 'com.github.z-chu.RxCache:rxcache:3.0.0'
50 | ```
51 |
52 | **可添加 Kotlin 扩展,解决泛型擦除问题**
53 | ```groovy
54 | implementation 'com.github.z-chu.RxCache:rxcache-kotlin:2.3.5'
55 | ```
56 |
57 | ### 首先创建一个 RxCache 实例
58 |
59 |
60 |
61 | ```java
62 | rxCache = new RxCache.Builder()
63 | .appVersion(1)//当版本号改变,缓存路径下存储的所有数据都会被清除掉
64 | .diskDir(new File(getCacheDir().getPath() + File.separator + "data-cache"))
65 | .diskConverter(new GsonDiskConverter())//支持Serializable、Json(GsonDiskConverter)
66 | .memoryMax(2*1024*1024)
67 | .diskMax(20*1024*1024)
68 | .build();
69 | ```
70 | 再使用 `compose()`操作符变换, 注意把<~>替换成你的数据类型
71 | ```java
72 | observable
73 | .compose(rxCache.<~>>transformObservable("custom_key", type, CacheStrategy.firstCache()))
74 | .subscribe(new Observer>() {
75 | ...
76 | @Override
77 | public void onNext(CacheResult<~> cacheResult) {
78 | Object data=cacheResult.getData();//获取你的数据
79 | }
80 | ...
81 | }
82 |
83 | ```
84 | ## Retrofit
85 |
86 | 在如果你使用的是 [retrofit](https://github.com/square/retrofit) 那可原有代码的基础上,仅需2行代码搞定,**一步到位!!!**
87 |
88 | Observable 调用
89 | ```java
90 | //注意在 <~> 中声明数据源的类型
91 | .compose(rxCache.<~>transformObservable(key,type,CacheStrategy.firstCache()))
92 | .map(new CacheResult.MapFunc<~>())
93 | ```
94 | Flowable 调用
95 | ```java
96 | .compose(rxCache.<~>transformFlowable(key,type,CacheStrategy.firstCache()))
97 | .map(new CacheResult.MapFunc<~>())
98 | ```
99 | 在这里声明缓存策略即可,不影响原有代码结构
100 |
101 | 如何你纠结 Key 值的取名,建议使用 **("方法名"+"参数名:"+"加参数值")**
102 |
103 |
104 | ## CacheStrategy
105 | 在`CacheStrategy` 类中提供如下缓存策略:
106 |
107 | 策略选择 | 摘要
108 | ------------------------- | -------
109 | firstRemote() | 优先网络
110 | firstCache() |优先缓存
111 | firstCacheTimeout(milliSecond) |优先缓存,并设置超时时间
112 | onlyRemote() | 仅加载网络,但数据依然会被缓存
113 | onlyCache() | 仅加载缓存
114 | cacheAndRemote() | 先加载缓存,后加载网络
115 | none() | 仅加载网络,不缓存
116 |
117 | 缓存的保存会在数据响应后用异步的方式保存,不会影响数据的响应时间。
118 |
119 | 如需要用同步方式保存,每个策略都有对应的同步保存方式
120 | 如: `CacheStrategy.firstRemoteSync()`
121 | 使用同步保存方式,数据会在缓存写入完以后才响应。
122 |
123 |
124 | ## CacheResult
125 | `CacheResult` 类,包含的属性如下:
126 |
127 | ```java
128 | public class CacheResult {
129 | private ResultFrom from;//数据来源,原始observable、内存或硬盘
130 | private String key;
131 | private T data; // 数据
132 | private long timestamp; //数据写入到缓存时的时间戳,如果来自原始observable则为0
133 | ...
134 | }
135 | ```
136 |
137 |
138 | ## Default rxCache
139 | 你也可以使用默认的 `RxCache`:
140 |
141 | 初始化默认的 `RxCache`
142 | ```java
143 | RxCache.initializeDefault(rxcache)
144 | ```
145 | 再这样使用
146 | ```java
147 | observable
148 | .compose(RxCache.getDefault().<~>>transformObservable("custom_key", type, strategy))
149 | ...
150 | ```
151 | 如果不初始化默认的 `RxCache`,这样使用缓存会保存到 `Environment.getDownloadCacheDirectory()`
且 `appVersion` 会永远为 `1`
152 |
153 |
154 | ## Kotlin
155 | **推荐使用 kotlin** ,规避了泛型擦除,可不传 `type`, 无比简单 :
156 |
157 | ```kotlin
158 | observable
159 | .rxCache("custom_key", strategy) //这样会使用默认的 RxCache ,你也可以传入任意 rxcache 使用
160 | .subscribe(object : Observer> {
161 | ...
162 | }
163 |
164 | ```
165 |
166 |
167 |
168 |
169 |
170 |
171 | ## 泛型
172 | 因为泛型擦除的原因,遇到 List<~> 这样的泛型时可以这样使用:
173 |
174 | ```java
175 | // <~> 为List元素的数据类型
176 | .compose(rxCache.>transformer("custom_key", new TypeToken>() {}.getType(), strategy))
177 | ```
178 |
179 | 没有泛型时 Type 直接传 Class 即可
180 | ```java
181 | .compose(rxCache.transformer("custom_key",Bean.class, strategy))
182 | ```
183 |
184 | **如果你使用 Kotlin 则没有这个问题**
185 | ```kotlin
186 | .rxCache(rxcache,"custom_key", strategy)
187 | ```
188 |
189 |
190 |
191 | ## 基础用法
192 |
193 | ### 保存缓存:
194 | 如 保存字符串到内存和硬盘:
195 | ```java
196 | rxCache
197 | .save("test_key1","RxCache is simple", CacheTarget.MemoryAndDisk)
198 | .subscribeOn(Schedulers.io())
199 | .subscribe();
200 | ```
201 | 保存方式提供了 3 种选择:
202 | ```java
203 | public enum CacheTarget {
204 | Memory,
205 | Disk,
206 | MemoryAndDisk;
207 | ...
208 | }
209 | ```
210 |
211 |
212 | ### 读取缓存:
213 | 读取的顺序会按照内存-->硬盘的顺序读取
214 | 如 读取缓存中的字符串:
215 | ```java
216 | rxCache
217 | .load("test_key1", String.class)
218 | .map(new CacheResult.MapFunc())
219 | .subscribe(new Consumer() {
220 | @Override
221 | public void accept(String value) throws Exception {
222 |
223 | }
224 | });
225 | ```
226 |
227 | 同步获取缓存:
228 | ```java
229 | CacheResult = rxCache.loadSync("test_key1", String.class);
230 | ```
231 |
232 |
233 |
234 | ## 混淆配置
235 | 本 Library 不需求添加额外混淆配置,所以代码都可被混淆
236 |
237 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.3.21'
5 | repositories {
6 | jcenter()
7 | maven {
8 | url 'https://maven.google.com/'
9 | name 'Google'
10 | }
11 | google()
12 | }
13 | dependencies {
14 | classpath 'com.android.tools.build:gradle:3.3.0'
15 |
16 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.0'
17 | classpath "guru.stefma.bintrayrelease:bintrayrelease:1.1.1"
18 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
19 | // NOTE: Do not place your application dependencies here; they belong
20 | // in the individual module build.gradle files
21 | }
22 |
23 | }
24 |
25 | allprojects {
26 | repositories {
27 | jcenter()
28 | mavenCentral()
29 | maven { url "https://jitpack.io" }
30 | maven{url 'https://dl.bintray.com/zchu/maven/'}
31 | maven {
32 | url 'https://maven.google.com/'
33 | name 'Google'
34 | }
35 | }
36 |
37 | tasks.withType(Javadoc) {
38 | options{ encoding "UTF-8"
39 | charSet 'UTF-8'
40 | links "http://docs.oracle.com/javase/7/docs/api"
41 | }
42 | }
43 | /* gradle.projectsEvaluated {
44 | tasks.withType(JavaCompile) {
45 | options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
46 | }
47 | }*/
48 | }
49 |
50 | task clean(type: Delete) {
51 | delete rootProject.buildDir
52 | }
53 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | android.enableJetifier=true
2 | android.useAndroidX=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/z-chu/RxCache/f8ce1751508f1684ff68eb770e90f5f3208e30fd/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Feb 15 13:36:39 SGT 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | org.gradle.daemon=true
7 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
8 | org.gradle.parallel=true
9 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/rxcache-kotlin/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: "guru.stefma.bintrayrelease"
4 |
5 | android {
6 | compileSdkVersion 28
7 | lintOptions {
8 | abortOnError false
9 | checkReleaseBuilds false
10 | }
11 | }
12 |
13 | dependencies {
14 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
15 | compileOnly 'com.google.code.gson:gson:2.8.5'
16 | compileOnly 'io.reactivex.rxjava2:rxjava:2.2.0'
17 | compileOnly project(':rxcache')
18 | }
19 |
20 | version = "2.3.5"
21 | group = "com.zchu"
22 | androidArtifact { // 2
23 | artifactId = "rxcache-kotlin"
24 | }
25 |
26 | publish {
27 | userOrg = 'zchu'
28 | desc = 'This is a cache library for android'
29 | website = 'https://github.com/z-chu/RxCache'
30 | }
31 | repositories {
32 | mavenCentral()
33 | }
34 | tasks.withType(Javadoc).all { enabled = false }
--------------------------------------------------------------------------------
/rxcache-kotlin/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/rxcache-kotlin/src/main/java/com/zchu/rxcache/kotlin/RxCache.kt:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.kotlin
2 |
3 | import com.google.gson.reflect.TypeToken
4 | import com.zchu.rxcache.RxCache
5 | import com.zchu.rxcache.data.CacheResult
6 | import com.zchu.rxcache.stategy.IFlowableStrategy
7 | import com.zchu.rxcache.stategy.IObservableStrategy
8 | import io.reactivex.*
9 |
10 | inline fun RxCache.load(key: String): Observable> {
11 | return load(key, object : TypeToken() {}.type)
12 | }
13 |
14 | inline fun RxCache.load2Flowable(key: String): Flowable> {
15 | return load2Flowable(key, object : TypeToken() {}.type, BackpressureStrategy.LATEST)
16 | }
17 |
18 | inline fun RxCache.load2Flowable(key: String, backpressureStrategy: BackpressureStrategy): Flowable> {
19 | return load2Flowable(key, object : TypeToken() {}.type, backpressureStrategy)
20 | }
21 |
22 | inline fun RxCache.transformObservable(key: String, strategy: IObservableStrategy): ObservableTransformer> {
23 | return transformObservable(key, object : TypeToken() {}.type, strategy)
24 | }
25 |
26 | inline fun RxCache.transformFlowable(key: String, strategy: IFlowableStrategy): FlowableTransformer> {
27 | return transformFlowable(key, object : TypeToken() {}.type, strategy)
28 | }
29 |
30 |
31 | inline fun Observable.rxCache(key: String, strategy: IObservableStrategy): Observable> {
32 | return this.rxCache(RxCache.getDefault(), key, strategy)
33 | }
34 |
35 | inline fun Observable.rxCache(rxCache: RxCache, key: String, strategy: IObservableStrategy): Observable> {
36 | return this.compose>(rxCache.transformObservable(key, object : TypeToken() {}.type, strategy))
37 | }
38 |
39 | inline fun Flowable.rxCache(key: String, strategy: IFlowableStrategy): Flowable> {
40 | return this.rxCache(RxCache.getDefault(), key, strategy)
41 | }
42 |
43 | inline fun Flowable.rxCache(rxCache: RxCache, key: String, strategy: IFlowableStrategy): Flowable> {
44 | return this.compose>(rxCache.transformFlowable(key, object : TypeToken() {}.type, strategy))
45 | }
46 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/rxcache/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: "guru.stefma.bintrayrelease"
3 |
4 | android {
5 | compileSdkVersion 28
6 |
7 | buildTypes {
8 | release {
9 | minifyEnabled false
10 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
11 | }
12 | }
13 | lintOptions {
14 | abortOnError false
15 | }
16 |
17 | }
18 |
19 | dependencies {
20 | compileOnly 'androidx.legacy:legacy-support-v4:1.0.0'
21 | implementation 'io.reactivex.rxjava2:rxjava:2.2.0'
22 | implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
23 | implementation 'com.google.code.gson:gson:2.8.5'
24 | implementation 'com.jakewharton:disklrucache:2.0.2'
25 | }
26 |
27 |
28 | version = "2.3.5"
29 | group = "com.zchu"
30 | androidArtifact { // 2
31 | artifactId = "rxcache"
32 | }
33 |
34 | publish {
35 | userOrg = 'zchu'
36 | desc = 'This is a cache library for android'
37 | website = 'https://github.com/z-chu/RxCache'
38 | }
39 |
--------------------------------------------------------------------------------
/rxcache/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 D:\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 |
--------------------------------------------------------------------------------
/rxcache/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/CacheCore.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache;
2 |
3 |
4 | import com.zchu.rxcache.data.CacheResult;
5 | import com.zchu.rxcache.data.ResultFrom;
6 |
7 | import java.io.IOException;
8 | import java.lang.reflect.Type;
9 |
10 | import androidx.annotation.Nullable;
11 |
12 | /**
13 | * 缓存核心
14 | * 作者: 赵成柱 on 2016/9/9
15 | */
16 | class CacheCore {
17 |
18 | @Nullable
19 | private LruMemoryCache memory;
20 | @Nullable
21 | private LruDiskCache disk;
22 |
23 | CacheCore(@Nullable LruMemoryCache memory, @Nullable LruDiskCache disk) {
24 | this.memory = memory;
25 | this.disk = disk;
26 | }
27 |
28 |
29 | /**
30 | * 读取
31 | */
32 | CacheResult load(String key, Type type) {
33 | if (memory != null) {
34 | CacheHolder result = memory.load(key);
35 | if (result != null) {
36 | return new CacheResult<>(ResultFrom.Memory, key, result.data, result.timestamp);
37 | }
38 | }
39 | if (disk != null) {
40 | CacheHolder result = disk.load(key, type);
41 | if (result != null) {
42 | return new CacheResult<>(ResultFrom.Disk, key, result.data, result.timestamp);
43 | }
44 | }
45 | return null;
46 | }
47 |
48 | /**
49 | * 保存
50 | */
51 | boolean save(String key, T value, CacheTarget target) {
52 | if (value == null) { //如果要保存的值为空,则删除
53 | boolean memoryRemove = true;
54 | if (memory != null) {
55 | memoryRemove = memory.remove(key);
56 | }
57 | boolean diskRemove = true;
58 | if (disk != null) {
59 | diskRemove = disk.remove(key);
60 | }
61 | return memoryRemove && diskRemove;
62 | }
63 | boolean save = false;
64 | if (target.supportMemory() && memory != null) {
65 | save = memory.save(key, value);
66 | }
67 | if (target.supportDisk() && disk != null) {
68 | return disk.save(key, value);
69 | }
70 | return save;
71 | }
72 |
73 | /**
74 | * 是否包含
75 | */
76 | boolean containsKey(String key) {
77 | return (memory != null && memory.containsKey(key)) || (disk != null && disk.containsKey(key));
78 | }
79 |
80 | /**
81 | * 删除缓存
82 | */
83 | boolean remove(String key) {
84 | boolean isRemove = true;
85 | if (memory != null) {
86 | isRemove = memory.remove(key);
87 | }
88 | if (disk != null) {
89 | isRemove = isRemove & disk.remove(key);
90 | }
91 | return isRemove;
92 | }
93 |
94 | /**
95 | * 清空缓存
96 | */
97 | void clear() throws IOException {
98 | if (memory != null) {
99 | memory.clear();
100 | }
101 | if (disk != null) {
102 | disk.clear();
103 | }
104 | }
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/CacheHolder.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache;
2 |
3 | public class CacheHolder {
4 |
5 | public CacheHolder(T data, long timestamp) {
6 | this.data = data;
7 | this.timestamp = timestamp;
8 | }
9 |
10 | public T data;
11 | public long timestamp;
12 | }
13 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/CacheTarget.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache;
2 |
3 | /**
4 | * 缓存目标
5 | * 作者: 赵成柱 on 2016/9/9
6 | */
7 | public enum CacheTarget {
8 | Memory,
9 | Disk,
10 | MemoryAndDisk;
11 |
12 | public boolean supportMemory() {
13 | return this==Memory || this== MemoryAndDisk;
14 | }
15 |
16 | public boolean supportDisk() {
17 | return this==Disk || this== MemoryAndDisk;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/LruDiskCache.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache;
2 |
3 | import com.jakewharton.disklrucache.DiskLruCache;
4 | import com.zchu.rxcache.diskconverter.IDiskConverter;
5 | import com.zchu.rxcache.utils.LogUtils;
6 |
7 | import java.io.File;
8 | import java.io.IOException;
9 | import java.io.InputStream;
10 | import java.io.OutputStream;
11 | import java.lang.reflect.Type;
12 |
13 | /**
14 | * Created by Z.Chu on 2016/9/10.
15 | */
16 | public class LruDiskCache {
17 | private IDiskConverter mDiskConverter;
18 | private DiskLruCache mDiskLruCache;
19 |
20 |
21 | public LruDiskCache(IDiskConverter diskConverter, File diskDir, int appVersion, long diskMaxSize) {
22 | this.mDiskConverter = diskConverter;
23 | try {
24 | mDiskLruCache = DiskLruCache.open(diskDir, appVersion, 2, diskMaxSize);
25 | } catch (IOException e) {
26 | LogUtils.log(e);
27 | }
28 | }
29 |
30 | public CacheHolder load(String key, Type type) {
31 | if (mDiskLruCache == null) {
32 | return null;
33 | }
34 | try {
35 | DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
36 | if (snapshot != null) {
37 | InputStream source = snapshot.getInputStream(0);
38 | T value = mDiskConverter.load(source, type);
39 | long timestamp = 0;
40 | String string = snapshot.getString(1);
41 | if (string != null) {
42 | timestamp = Long.parseLong(string);
43 | }
44 | snapshot.close();
45 | return new CacheHolder<>(value, timestamp);
46 | }
47 | } catch (IOException e) {
48 | LogUtils.log(e);
49 | }
50 | return null;
51 | }
52 |
53 |
54 | public boolean save(String key, T value) {
55 | if (mDiskLruCache == null) {
56 | return false;
57 | }
58 | //如果要保存的值为空,则删除
59 | if (value == null) {
60 | return remove(key);
61 | }
62 | DiskLruCache.Editor edit = null;
63 | try {
64 | edit = mDiskLruCache.edit(key);
65 | OutputStream sink = edit.newOutputStream(0);
66 | mDiskConverter.writer(sink, value);
67 | long l = System.currentTimeMillis();
68 | edit.set(1, String.valueOf(l));
69 | edit.commit();
70 | LogUtils.log("save: value=" + value + " , status=" + true);
71 | return true;
72 | } catch (IOException e) {
73 | LogUtils.log(e);
74 | if (edit != null) {
75 | try {
76 | edit.abort();
77 | } catch (IOException e1) {
78 | LogUtils.log(e1);
79 | }
80 | }
81 | LogUtils.log("save: value=" + value + " , status=" + false);
82 | }
83 | return false;
84 | }
85 |
86 |
87 | public boolean containsKey(String key) {
88 | if (mDiskLruCache != null) {
89 | try {
90 | return mDiskLruCache.get(key) != null;
91 | } catch (IOException e) {
92 | LogUtils.log(e);
93 | }
94 | }
95 | return false;
96 | }
97 |
98 | /**
99 | * 删除缓存
100 | */
101 | public boolean remove(String key) {
102 | if (mDiskLruCache != null) {
103 | try {
104 | return mDiskLruCache.remove(key);
105 | } catch (IOException e) {
106 | LogUtils.log(e);
107 | }
108 | }
109 | return false;
110 | }
111 |
112 | public void clear() throws IOException {
113 | if (mDiskLruCache != null) {
114 | deleteContents(mDiskLruCache.getDirectory());
115 | }
116 | }
117 |
118 | private static void deleteContents(File dir) throws IOException {
119 | File[] files = dir.listFiles();
120 | if (files == null) {
121 | throw new IOException("not a readable directory: " + dir);
122 | }
123 | for (File file : files) {
124 | if (file.isDirectory()) {
125 | deleteContents(file);
126 | }
127 | if (!file.delete()) {
128 | throw new IOException("failed to delete file: " + file);
129 | }
130 | }
131 | }
132 |
133 |
134 | }
135 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/LruMemoryCache.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache;
2 |
3 |
4 | import android.graphics.Bitmap;
5 |
6 | import com.zchu.rxcache.utils.LogUtils;
7 | import com.zchu.rxcache.utils.MemorySizeOf;
8 | import com.zchu.rxcache.utils.Occupy;
9 |
10 | import java.util.HashMap;
11 |
12 | import androidx.collection.LruCache;
13 |
14 | /**
15 | * Created by Chu on 2016/9/10.
16 | */
17 | public class LruMemoryCache {
18 | private LruCache mCache;
19 | private HashMap memorySizeMap;//储存初次加入缓存的size,规避对象在内存中大小变化造成的测量出错
20 | private HashMap timestampMap;
21 | private Occupy occupy;
22 |
23 | public LruMemoryCache(final int cacheSize) {
24 | memorySizeMap = new HashMap<>();
25 | timestampMap = new HashMap<>();
26 | byte to = 0;
27 | byte t4 = 4;
28 | occupy = new Occupy(to, to, t4);
29 | mCache = new LruCache(cacheSize) {
30 | @Override
31 | protected int sizeOf(String key, Object value) {
32 | Integer integer = memorySizeMap.get(key);
33 | if (integer == null) {
34 | integer = countSize(value);
35 | memorySizeMap.put(key, integer);
36 | }
37 | return integer;
38 | }
39 |
40 | @Override
41 | protected void entryRemoved(boolean evicted, String key, Object oldValue, Object newValue) {
42 | super.entryRemoved(evicted, key, oldValue, newValue);
43 | memorySizeMap.remove(key);
44 | timestampMap.remove(key);
45 | }
46 | };
47 | }
48 |
49 | public CacheHolder load(String key) {
50 | T value = (T) mCache.get(key);
51 | if (value != null) {
52 | return new CacheHolder<>(value, timestampMap.get(key));
53 | }
54 | return null;
55 | }
56 |
57 | public boolean save(String key, T value) {
58 | if (null != value) {
59 |
60 | mCache.put(key, value);
61 | timestampMap.put(key, System.currentTimeMillis());
62 | }
63 | return true;
64 | }
65 |
66 | public boolean containsKey(String key) {
67 | return mCache.get(key) != null;
68 | }
69 |
70 | /**
71 | * 删除缓存
72 | */
73 | public boolean remove(String key) {
74 | Object remove = mCache.remove(key);
75 | if (remove != null) {
76 | memorySizeMap.remove(key);
77 | timestampMap.remove(key);
78 | return true;
79 | }
80 | return false;
81 | }
82 |
83 | public void clear() {
84 | mCache.evictAll();
85 | }
86 |
87 | protected int countSize(Object value) {
88 | if (value == null) {
89 | return 0;
90 | }
91 |
92 | // 更优良的内存大小算法
93 | int size;
94 | if (value instanceof Bitmap) {
95 | LogUtils.debug("Bitmap");
96 | size = MemorySizeOf.sizeOf((Bitmap) value);
97 | } else {
98 | size = occupy.occupyof(value);
99 | }
100 | LogUtils.debug("size=" + size + " value=" + value);
101 | return size > 0 ? size : 1;
102 | }
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/RxCache.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache;
2 |
3 | import android.os.Environment;
4 | import android.os.StatFs;
5 |
6 | import com.zchu.rxcache.data.CacheResult;
7 | import com.zchu.rxcache.diskconverter.IDiskConverter;
8 | import com.zchu.rxcache.diskconverter.SerializableDiskConverter;
9 | import com.zchu.rxcache.stategy.IFlowableStrategy;
10 | import com.zchu.rxcache.stategy.IObservableStrategy;
11 | import com.zchu.rxcache.utils.LogUtils;
12 |
13 | import org.reactivestreams.Publisher;
14 |
15 | import java.io.File;
16 | import java.io.IOException;
17 | import java.lang.reflect.Type;
18 | import java.security.MessageDigest;
19 |
20 | import androidx.annotation.NonNull;
21 | import io.reactivex.BackpressureStrategy;
22 | import io.reactivex.Flowable;
23 | import io.reactivex.FlowableEmitter;
24 | import io.reactivex.FlowableOnSubscribe;
25 | import io.reactivex.FlowableTransformer;
26 | import io.reactivex.Observable;
27 | import io.reactivex.ObservableEmitter;
28 | import io.reactivex.ObservableOnSubscribe;
29 | import io.reactivex.ObservableSource;
30 | import io.reactivex.ObservableTransformer;
31 |
32 |
33 | /**
34 | * RxJava remote data cache processing library, support Serializable, JSON
35 | * 作者: 赵成柱 on 2016/9/9 0012.
36 | */
37 | public final class RxCache {
38 |
39 |
40 | private final CacheCore cacheCore;
41 |
42 | private static RxCache sDefaultRxCache;
43 |
44 | @NonNull
45 | public static RxCache getDefault() {
46 | if (sDefaultRxCache == null) {
47 | sDefaultRxCache = new RxCache.Builder()
48 | .appVersion(1)
49 | .diskDir(Environment.getDownloadCacheDirectory())
50 | .diskConverter(new SerializableDiskConverter())
51 | .setDebug(true)
52 | .build();
53 |
54 | }
55 | return sDefaultRxCache;
56 | }
57 |
58 | public static void initializeDefault(RxCache rxCache) {
59 | if (sDefaultRxCache == null) {
60 | RxCache.sDefaultRxCache = rxCache;
61 | } else {
62 | LogUtils.log("You need to initialize it before using the default rxCache and only initialize it once");
63 | }
64 | }
65 |
66 |
67 | private RxCache(CacheCore cacheCore) {
68 | this.cacheCore = cacheCore;
69 | }
70 |
71 | /**
72 | * notice: Deprecated! Use {@link #transformObservable(String, Type, IObservableStrategy)} ()} replace.
73 | */
74 | @Deprecated
75 | public ObservableTransformer> transformer(String key, Type type, IObservableStrategy strategy) {
76 | return transformObservable(key, type, strategy);
77 | }
78 |
79 | public ObservableTransformer> transformObservable(final String key, final Type type, final IObservableStrategy strategy) {
80 | return new ObservableTransformer>() {
81 | @Override
82 | public ObservableSource> apply(Observable tObservable) {
83 | return strategy.execute(RxCache.this, key, tObservable, type);
84 | }
85 | };
86 | }
87 |
88 | public FlowableTransformer> transformFlowable(final String key, final Type type, final IFlowableStrategy strategy) {
89 | return new FlowableTransformer>() {
90 | @Override
91 | public Publisher> apply(Flowable flowable) {
92 | return strategy.flow(RxCache.this, key, flowable, type);
93 | }
94 | };
95 | }
96 |
97 |
98 | /**
99 | * 同步读取缓存
100 | * 会阻塞主线程,请在子线程调用
101 | */
102 | public CacheResult loadSync(final String key, final Type type) {
103 | return cacheCore.load(getMD5MessageDigest(key), type);
104 | }
105 |
106 |
107 | /**
108 | * 读取
109 | */
110 | public Observable> load(final String key, final Type type) {
111 | return Observable.create(new ObservableOnSubscribe>() {
112 | @Override
113 | public void subscribe(ObservableEmitter> observableEmitter) throws Exception {
114 | CacheResult load = cacheCore.load(getMD5MessageDigest(key), type);
115 | if (!observableEmitter.isDisposed()) {
116 | if (load != null) {
117 | observableEmitter.onNext(load);
118 | observableEmitter.onComplete();
119 | } else {
120 | observableEmitter.onError(new NullPointerException("Not find the key corresponding to the cache"));
121 | }
122 | }
123 | }
124 | });
125 | }
126 |
127 | /**
128 | * 读取
129 | */
130 | public Flowable> load2Flowable(String key, Type type) {
131 | return load2Flowable(key, type, BackpressureStrategy.LATEST);
132 | }
133 |
134 | public Flowable> load2Flowable(final String key, final Type type, BackpressureStrategy backpressureStrategy) {
135 | return Flowable.create(new FlowableOnSubscribe>() {
136 | @Override
137 | public void subscribe(FlowableEmitter> flowableEmitter) throws Exception {
138 | CacheResult load = cacheCore.load(getMD5MessageDigest(key), type);
139 | if (!flowableEmitter.isCancelled()) {
140 | if (load != null) {
141 | flowableEmitter.onNext(load);
142 | flowableEmitter.onComplete();
143 | } else {
144 | flowableEmitter.onError(new NullPointerException("Not find the key corresponding to the cache"));
145 | }
146 | }
147 | }
148 | }, backpressureStrategy);
149 | }
150 |
151 |
152 | public Observable save(final String key, final T value) {
153 | return save(key, value, CacheTarget.MemoryAndDisk);
154 | }
155 |
156 | /**
157 | * 保存
158 | */
159 | public Observable save(final String key, final T value, final CacheTarget target) {
160 | return Observable.create(new ObservableOnSubscribe() {
161 | @Override
162 | public void subscribe(ObservableEmitter observableEmitter) throws Exception {
163 | boolean save = cacheCore.save(getMD5MessageDigest(key), value, target);
164 | if (!observableEmitter.isDisposed()) {
165 | observableEmitter.onNext(save);
166 | observableEmitter.onComplete();
167 | }
168 | }
169 | });
170 | }
171 |
172 | /**
173 | * 保存
174 | */
175 | public Flowable save2Flowable(final String key, final T value, final CacheTarget target) {
176 | return save2Flowable(key, value, target, BackpressureStrategy.LATEST);
177 | }
178 |
179 | /**
180 | * 保存
181 | */
182 | public Flowable save2Flowable(final String key, final T value, final CacheTarget target, BackpressureStrategy strategy) {
183 | return Flowable.create(new FlowableOnSubscribe() {
184 | @Override
185 | public void subscribe(FlowableEmitter flowableEmitter) throws Exception {
186 | boolean save = cacheCore.save(getMD5MessageDigest(key), value, target);
187 | if (!flowableEmitter.isCancelled()) {
188 | flowableEmitter.onNext(save);
189 | flowableEmitter.onComplete();
190 | }
191 | }
192 | }, strategy);
193 | }
194 |
195 | /**
196 | * 是否包含
197 | *
198 | * @param key
199 | * @return
200 | */
201 | public boolean containsKey(final String key) {
202 | return cacheCore.containsKey(getMD5MessageDigest(key));
203 | }
204 |
205 | /**
206 | * 删除缓存
207 | */
208 | public boolean remove(final String key) {
209 | return cacheCore.remove(getMD5MessageDigest(key));
210 | }
211 |
212 | /**
213 | * 清空缓存
214 | */
215 | public Observable clear() {
216 | return Observable.create(new ObservableOnSubscribe() {
217 | @Override
218 | public void subscribe(ObservableEmitter observableEmitter) throws Exception {
219 | try {
220 | cacheCore.clear();
221 | if (!observableEmitter.isDisposed()) {
222 | observableEmitter.onNext(true);
223 | observableEmitter.onComplete();
224 | }
225 | } catch (IOException e) {
226 | LogUtils.log(e);
227 | if (!observableEmitter.isDisposed()) {
228 | observableEmitter.onError(e);
229 | }
230 | }
231 | }
232 | });
233 | }
234 |
235 | /**
236 | * 清空缓存
237 | */
238 | public void clear2() throws IOException {
239 | cacheCore.clear();
240 | }
241 |
242 |
243 | /**
244 | * 构造器
245 | */
246 | public static final class Builder {
247 | private static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
248 | private static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
249 | private static final int DEFAULT_MEMORY_CACHE_SIZE = (int) (Runtime.getRuntime().maxMemory() / 8);//运行内存的8分之1
250 | private Integer memoryMaxSize;
251 | private Long diskMaxSize;
252 | private int appVersion;
253 | private File diskDir;
254 | private IDiskConverter diskConverter;
255 |
256 | public Builder() {
257 | }
258 |
259 | /**
260 | * 不设置,默认为运行内存的8分之1.设置0,或小于0,则不开启内存缓存;
261 | */
262 | public Builder memoryMax(int maxSize) {
263 | this.memoryMaxSize = maxSize;
264 | return this;
265 | }
266 |
267 | /**
268 | * 不设置,默认为1.需要注意的是,每当版本号改变,缓存路径下存储的所有数据都会被清除掉,所有的数据都应该从网上重新获取.
269 | */
270 | public Builder appVersion(int appVersion) {
271 | this.appVersion = appVersion;
272 | return this;
273 | }
274 |
275 | public Builder diskDir(File directory) {
276 | this.diskDir = directory;
277 | return this;
278 | }
279 |
280 |
281 | public Builder diskConverter(IDiskConverter converter) {
282 | this.diskConverter = converter;
283 | return this;
284 | }
285 |
286 | /**
287 | * 不设置, 默为认50MB.设置0,或小于0,则不开启硬盘缓存;
288 | */
289 | public Builder diskMax(long maxSize) {
290 | this.diskMaxSize = maxSize;
291 | return this;
292 | }
293 |
294 | public Builder setDebug(boolean debug) {
295 | LogUtils.DEBUG = debug;
296 | return this;
297 | }
298 |
299 | public RxCache build() {
300 | appVersion = Math.max(1, this.appVersion);
301 | if (diskDir != null) {
302 | if (!diskDir.exists() && !diskDir.mkdirs()) {
303 | throw new RuntimeException("can't make dirs in " + diskDir.getAbsolutePath());
304 | }
305 | if (this.diskConverter == null) {
306 | this.diskConverter = new SerializableDiskConverter();
307 | }
308 | if (diskMaxSize == null) {
309 | diskMaxSize = calculateDiskCacheSize(diskDir);
310 | }
311 | }
312 |
313 | if (memoryMaxSize == null) {
314 | memoryMaxSize = DEFAULT_MEMORY_CACHE_SIZE;
315 | }
316 |
317 | LruMemoryCache memoryCache = null;
318 | if (memoryMaxSize > 0) {
319 | memoryCache = new LruMemoryCache(memoryMaxSize);
320 | }
321 | LruDiskCache lruDiskCache = null;
322 | if (diskDir != null && diskMaxSize > 0) {
323 | lruDiskCache = new LruDiskCache(diskConverter, diskDir, appVersion, diskMaxSize);
324 | }
325 | CacheCore cacheCore = new CacheCore(memoryCache, lruDiskCache);
326 | return new RxCache(cacheCore);
327 | }
328 |
329 | private static long calculateDiskCacheSize(File dir) {
330 | long size = 0;
331 |
332 | try {
333 | StatFs statFs = new StatFs(dir.getAbsolutePath());
334 | long available = ((long) statFs.getBlockCount()) * statFs.getBlockSize();
335 | // Target 2% of the total space.
336 | size = available / 50;
337 | } catch (IllegalArgumentException ignored) {
338 | LogUtils.log(ignored);
339 | }
340 | // Bound inside min/max size for disk cache.
341 | return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE);
342 | }
343 |
344 | }
345 |
346 | static String getMD5MessageDigest(String buffer) {
347 | char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
348 | try {
349 | MessageDigest mdTemp = MessageDigest.getInstance("MD5");
350 | mdTemp.update(buffer.getBytes());
351 | byte[] md = mdTemp.digest();
352 | int j = md.length;
353 | char str[] = new char[j * 2];
354 | int k = 0;
355 | for (byte byte0 : md) {
356 | str[k++] = hexDigits[byte0 >>> 4 & 0xf];
357 | str[k++] = hexDigits[byte0 & 0xf];
358 | }
359 | return new String(str);
360 | } catch (Exception e) {
361 | LogUtils.log(e);
362 | return buffer;
363 | }
364 | }
365 |
366 | }
367 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/RxCacheHelper.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache;
2 |
3 | import android.annotation.SuppressLint;
4 |
5 | import com.zchu.rxcache.data.CacheResult;
6 | import com.zchu.rxcache.data.ResultFrom;
7 | import com.zchu.rxcache.utils.LogUtils;
8 |
9 | import org.reactivestreams.Publisher;
10 |
11 | import java.lang.reflect.Type;
12 | import java.util.ConcurrentModificationException;
13 |
14 | import io.reactivex.Flowable;
15 | import io.reactivex.Observable;
16 | import io.reactivex.ObservableSource;
17 | import io.reactivex.annotations.NonNull;
18 | import io.reactivex.functions.Consumer;
19 | import io.reactivex.functions.Function;
20 | import io.reactivex.schedulers.Schedulers;
21 |
22 | /**
23 | * author : zchu
24 | * date : 2017/10/9
25 | * desc : RxCache的帮助类
26 | */
27 |
28 | public class RxCacheHelper {
29 |
30 | public static Observable> loadCache(final RxCache rxCache, final String key, Type type, final boolean needEmpty) {
31 | Observable> observable = rxCache
32 | .load(key, type)
33 | .subscribeOn(Schedulers.io());
34 | if (needEmpty) {
35 | observable = observable
36 | .onErrorResumeNext(new Function>>() {
37 | @Override
38 | public ObservableSource extends CacheResult> apply(@NonNull Throwable throwable) throws Exception {
39 | return Observable.empty();
40 | }
41 | });
42 | }
43 | return observable;
44 | }
45 |
46 | public static Observable> loadRemote(final RxCache rxCache, final String key, Observable source, final CacheTarget target, final boolean needEmpty) {
47 | Observable> observable = source
48 | .map(new Function>() {
49 | @SuppressLint("CheckResult")
50 | @Override
51 | public CacheResult apply(@NonNull T t) throws Exception {
52 | LogUtils.debug("loadRemote result=" + t);
53 | rxCache.save(key, t, target)
54 | .subscribeOn(Schedulers.io())
55 | .subscribe(
56 | new Consumer() {
57 | @Override
58 | public void accept(@NonNull Boolean status) throws Exception {
59 | LogUtils.debug("save status => " + status);
60 | }
61 | },
62 | new Consumer() {
63 | @Override
64 | public void accept(@NonNull Throwable throwable) throws Exception {
65 | if (throwable instanceof ConcurrentModificationException) {
66 | LogUtils.log("Save failed, please use a synchronized cache strategy :", throwable);
67 | } else {
68 | LogUtils.log(throwable);
69 | }
70 | }
71 | });
72 | return new CacheResult<>(ResultFrom.Remote, key, t);
73 | }
74 | });
75 | if (needEmpty) {
76 | observable = observable
77 | .onErrorResumeNext(new Function>>() {
78 | @Override
79 | public ObservableSource extends CacheResult> apply(@NonNull Throwable throwable) throws Exception {
80 | return Observable.empty();
81 | }
82 | });
83 | }
84 | return observable;
85 | }
86 |
87 |
88 | public static Observable> loadRemoteSync(final RxCache rxCache, final String key, Observable source, final CacheTarget target, final boolean needEmpty) {
89 | Observable> observable = source
90 | .flatMap(new Function>>() {
91 | @Override
92 | public ObservableSource> apply(@NonNull T t) throws Exception {
93 | return saveCacheSync(rxCache, key, t, target);
94 | }
95 | });
96 | if (needEmpty) {
97 | observable = observable.onErrorResumeNext(new Function>>() {
98 | @Override
99 | public ObservableSource extends CacheResult> apply(@NonNull Throwable throwable) throws Exception {
100 | return Observable.empty();
101 | }
102 | });
103 | }
104 | return observable;
105 |
106 | }
107 |
108 | public static Observable> saveCacheSync(RxCache rxCache, final String key, final T t, CacheTarget target) {
109 | return rxCache.save(key, t, target)
110 | .map(new Function>() {
111 | @Override
112 | public CacheResult apply(@NonNull Boolean aBoolean) throws Exception {
113 | return new CacheResult<>(ResultFrom.Remote, key, t);
114 | }
115 | })
116 | .onErrorReturn(new Function>() {
117 | @Override
118 | public CacheResult apply(@NonNull Throwable throwable) throws Exception {
119 | return new CacheResult<>(ResultFrom.Remote, key, t);
120 | }
121 | });
122 | }
123 |
124 | public static Flowable> loadCacheFlowable(final RxCache rxCache, final String key, Type type, final boolean needEmpty) {
125 | Flowable> flowable = rxCache.load2Flowable(key, type);
126 | if (needEmpty) {
127 | flowable = flowable
128 | .onErrorResumeNext(new Function>>() {
129 | @Override
130 | public Publisher extends CacheResult> apply(@NonNull Throwable throwable) throws Exception {
131 | return Flowable.empty();
132 | }
133 | });
134 | }
135 | return flowable;
136 | }
137 |
138 | public static Flowable> loadRemoteFlowable(final RxCache rxCache, final String key, Flowable source, final CacheTarget target, final boolean needEmpty) {
139 | Flowable> flowable = source
140 | .map(new Function>() {
141 | @SuppressLint("CheckResult")
142 | @Override
143 | public CacheResult apply(@NonNull T t) throws Exception {
144 | LogUtils.debug("loadRemote result=" + t);
145 | rxCache.save(key, t, target)
146 | .subscribeOn(Schedulers.io())
147 | .subscribe(
148 | new Consumer() {
149 | @Override
150 | public void accept(@NonNull Boolean status) throws Exception {
151 | LogUtils.debug("save status => " + status);
152 | }
153 | },
154 | new Consumer() {
155 | @Override
156 | public void accept(@NonNull Throwable throwable) throws Exception {
157 | if (throwable instanceof ConcurrentModificationException) {
158 | LogUtils.log("Save failed, please use a synchronized cache strategy :", throwable);
159 | } else {
160 | LogUtils.log(throwable);
161 | }
162 | }
163 | });
164 | return new CacheResult<>(ResultFrom.Remote, key, t);
165 | }
166 | });
167 | if (needEmpty) {
168 | flowable = flowable
169 | .onErrorResumeNext(new Function>>() {
170 | @Override
171 | public Publisher extends CacheResult> apply(@NonNull Throwable throwable) throws Exception {
172 | return Flowable.empty();
173 | }
174 | });
175 | }
176 | return flowable;
177 | }
178 |
179 |
180 | public static Flowable> loadRemoteSyncFlowable(final RxCache rxCache, final String key, final Flowable source, final CacheTarget target, final boolean needEmpty) {
181 | Flowable> flowable = source
182 | .flatMap(new Function>>() {
183 | @Override
184 | public Publisher> apply(@NonNull T t) throws Exception {
185 | return saveCacheSyncFlowable(rxCache, key, t, target);
186 | }
187 | });
188 | if (needEmpty) {
189 | flowable = flowable.onErrorResumeNext(new Function>>() {
190 | @Override
191 | public Publisher extends CacheResult> apply(@NonNull Throwable throwable) throws Exception {
192 | return Flowable.empty();
193 | }
194 | });
195 | }
196 | return flowable;
197 | }
198 |
199 | public static Flowable> saveCacheSyncFlowable(RxCache rxCache, final String key, final T t, CacheTarget target) {
200 | return rxCache
201 | .save2Flowable(key, t, target)
202 | .map(new Function>() {
203 | @Override
204 | public CacheResult apply(@NonNull Boolean aBoolean) throws Exception {
205 | return new CacheResult<>(ResultFrom.Remote, key, t);
206 | }
207 | })
208 | .onErrorReturn(new Function>() {
209 | @Override
210 | public CacheResult apply(@NonNull Throwable throwable) throws Exception {
211 | return new CacheResult<>(ResultFrom.Remote, key, t);
212 | }
213 | });
214 | }
215 |
216 |
217 | }
218 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/data/CacheResult.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.data;
2 |
3 | import io.reactivex.functions.Function;
4 |
5 | /**
6 | * 数据
7 | */
8 | public class CacheResult {
9 |
10 | private ResultFrom from;
11 | private String key;
12 | private T data;
13 | private long timestamp;
14 |
15 | public CacheResult() {
16 | }
17 |
18 | public CacheResult(ResultFrom from, String key, T data) {
19 | this.from = from;
20 | this.key = key;
21 | this.data = data;
22 | }
23 |
24 | public CacheResult(ResultFrom from, String key, T data, long timestamp) {
25 | this.from = from;
26 | this.key = key;
27 | this.data = data;
28 | this.timestamp = timestamp;
29 | }
30 |
31 | public ResultFrom getFrom() {
32 | return from;
33 | }
34 |
35 | public void setFrom(ResultFrom from) {
36 | this.from = from;
37 | }
38 |
39 | public String getKey() {
40 | return key;
41 | }
42 |
43 | public void setKey(String key) {
44 | this.key = key;
45 | }
46 |
47 | public T getData() {
48 | return data;
49 | }
50 |
51 | public void setData(T data) {
52 | this.data = data;
53 | }
54 |
55 | public long getTimestamp() {
56 | return timestamp;
57 | }
58 |
59 | public void setTimestamp(long timestamp) {
60 | this.timestamp = timestamp;
61 | }
62 |
63 | @Override
64 | public String toString() {
65 | return "CacheResult{" +
66 | "from=" + from +
67 | ", key='" + key + '\'' +
68 | ", data=" + data +
69 | ", timestamp=" + timestamp +
70 | '}';
71 | }
72 |
73 |
74 | /**
75 | * 用于map操作符,只想拿CacheResult.data的数据
76 | *
77 | * @param Subscriber真正需要的数据类型,也就是Data部分的数据类型
78 | */
79 | public static class MapFunc implements Function, T> {
80 |
81 | @Override
82 | public T apply(CacheResult tCacheResult) throws Exception {
83 | if (tCacheResult != null) {
84 | return tCacheResult.getData();
85 | }
86 | return null;
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/data/ResultFrom.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.data;
2 |
3 | /**
4 | * 数据来源
5 | */
6 | public enum ResultFrom {
7 | Remote, Disk, Memory;
8 |
9 | public static boolean ifFromCache(ResultFrom from) {
10 | return from == Disk || from == Memory;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/diskconverter/GsonDiskConverter.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.diskconverter;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.JsonIOException;
5 | import com.google.gson.JsonSyntaxException;
6 | import com.google.gson.TypeAdapter;
7 | import com.google.gson.reflect.TypeToken;
8 | import com.google.gson.stream.JsonReader;
9 | import com.zchu.rxcache.utils.LogUtils;
10 | import com.zchu.rxcache.utils.Utils;
11 |
12 | import java.io.IOException;
13 | import java.io.InputStream;
14 | import java.io.InputStreamReader;
15 | import java.io.OutputStream;
16 | import java.lang.reflect.Type;
17 |
18 | /**
19 | * Created by Chu on 2017/2/28.
20 | */
21 |
22 | public class GsonDiskConverter implements IDiskConverter {
23 |
24 | private Gson mGson = new Gson();
25 |
26 |
27 | public GsonDiskConverter() {
28 | this(new Gson());
29 | }
30 |
31 | public GsonDiskConverter(Gson gson) {
32 | if (gson == null) throw new NullPointerException("gson == null");
33 | this.mGson = gson;
34 | }
35 |
36 |
37 | @Override
38 | public T load(InputStream source, Type type) {
39 |
40 | T value = null;
41 | try {
42 | TypeAdapter> adapter = mGson.getAdapter(TypeToken.get(type));
43 | JsonReader jsonReader = mGson.newJsonReader(new InputStreamReader(source));
44 | value = (T) adapter.read(jsonReader);
45 | } catch (JsonIOException | JsonSyntaxException e) {
46 | LogUtils.log(e);
47 | } catch (IOException e) {
48 | LogUtils.log(e);
49 | } finally {
50 | Utils.close(source);
51 | }
52 | return value;
53 | }
54 |
55 | @Override
56 | public boolean writer(OutputStream sink, Object data) {
57 | try {
58 |
59 | String json = mGson.toJson(data);
60 | byte[] bytes = json.getBytes();
61 | sink.write(bytes, 0, bytes.length);
62 | sink.flush();
63 | return true;
64 | } catch (JsonIOException | IOException e) {
65 | LogUtils.log(e);
66 | } finally {
67 | Utils.close(sink);
68 | }
69 | return false;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/diskconverter/IDiskConverter.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.diskconverter;
2 |
3 | import java.io.InputStream;
4 | import java.io.OutputStream;
5 | import java.lang.reflect.Type;
6 |
7 | /**
8 | * 通用转换器
9 | *
10 | * Created by Chu on 2016/9/10.
11 | */
12 | public interface IDiskConverter {
13 |
14 | /**
15 | * 读取
16 | *
17 | * @param source
18 | * @return
19 | */
20 | T load(InputStream source, Type type);
21 |
22 | /**
23 | * 写入
24 | *
25 | * @param sink
26 | * @param data
27 | * @return
28 | */
29 | boolean writer(OutputStream sink, Object data);
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/diskconverter/SerializableDiskConverter.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.diskconverter;
2 |
3 |
4 | import com.zchu.rxcache.utils.LogUtils;
5 | import com.zchu.rxcache.utils.Utils;
6 |
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 | import java.io.ObjectInputStream;
10 | import java.io.ObjectOutputStream;
11 | import java.io.OutputStream;
12 | import java.lang.reflect.Type;
13 |
14 |
15 | public class SerializableDiskConverter implements IDiskConverter {
16 |
17 | @Override
18 | public T load(InputStream source, Type type) {
19 | T value = null;
20 | ObjectInputStream oin = null;
21 | try {
22 | oin = new ObjectInputStream(source);
23 | value = (T) oin.readObject();
24 | } catch (IOException | ClassNotFoundException e) {
25 | LogUtils.log(e);
26 | } finally {
27 | Utils.close(oin);
28 | }
29 | return value;
30 | }
31 |
32 | @Override
33 | public boolean writer(OutputStream sink, Object data) {
34 | ObjectOutputStream oos = null;
35 | try {
36 | oos = new ObjectOutputStream(sink);
37 | oos.writeObject(data);
38 | oos.flush();
39 | return true;
40 | } catch (IOException e) {
41 | LogUtils.log(e);
42 | } finally {
43 | Utils.close(oos);
44 | }
45 | return false;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/CacheAndRemoteStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 | import com.zchu.rxcache.CacheTarget;
4 | import com.zchu.rxcache.RxCache;
5 | import com.zchu.rxcache.RxCacheHelper;
6 | import com.zchu.rxcache.data.CacheResult;
7 |
8 | import org.reactivestreams.Publisher;
9 |
10 | import java.lang.reflect.Type;
11 | import java.util.Arrays;
12 |
13 | import io.reactivex.Flowable;
14 | import io.reactivex.Observable;
15 | import io.reactivex.annotations.NonNull;
16 | import io.reactivex.functions.Predicate;
17 |
18 | /**
19 | * 先缓存,后网络
20 | * 作者: 赵成柱 on 2016/9/12 0012.
21 | */
22 | public final class CacheAndRemoteStrategy implements IStrategy {
23 | private boolean isSync;
24 |
25 | public CacheAndRemoteStrategy() {
26 | isSync = false;
27 | }
28 |
29 | public CacheAndRemoteStrategy(boolean isSync) {
30 | this.isSync = isSync;
31 | }
32 |
33 | @Override
34 | public Observable> execute(RxCache rxCache, String key, Observable source, Type type) {
35 | Observable> cache = RxCacheHelper.loadCache(rxCache, key, type, true);
36 | Observable> remote;
37 | if (isSync) {
38 | remote = RxCacheHelper.loadRemoteSync(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
39 | } else {
40 | remote = RxCacheHelper.loadRemote(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
41 | }
42 | return Observable.concatDelayError(Arrays.asList(cache, remote))
43 | .filter(new Predicate>() {
44 | @Override
45 | public boolean test(@NonNull CacheResult result) throws Exception {
46 | return result.getData() != null;
47 | }
48 | });
49 | }
50 |
51 | @Override
52 | public Publisher> flow(RxCache rxCache, String key, Flowable source, Type type) {
53 | Flowable> cache = RxCacheHelper.loadCacheFlowable(rxCache, key, type, true);
54 | Flowable> remote;
55 | if (isSync) {
56 | remote = RxCacheHelper.loadRemoteSyncFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
57 | } else {
58 | remote = RxCacheHelper.loadRemoteFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
59 | }
60 | return Flowable.concatDelayError(Arrays.asList(cache, remote))
61 | .filter(new Predicate>() {
62 | @Override
63 | public boolean test(@NonNull CacheResult result) throws Exception {
64 | return result.getData() != null;
65 | }
66 | });
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/CacheStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 | /**
4 | * Created by Chu on 2016/10/25.
5 | */
6 |
7 | public final class CacheStrategy {
8 |
9 |
10 |
11 |
12 | /**
13 | * 优先网络,缓存用异步的方式保存
14 | */
15 | public static IStrategy firstRemote() {
16 |
17 | return new FirstRemoteStrategy();
18 | }
19 |
20 | /**
21 | * 优先网络,缓存用同步的方式保存
22 | */
23 | public static IStrategy firstRemoteSync() {
24 | return new FirstRemoteStrategy(true);
25 | }
26 |
27 | /**
28 | * 优先缓存,缓存用异步的方式保存
29 | */
30 | public static IStrategy firstCache() {
31 | return new FirstCacheStrategy();
32 | }
33 |
34 | /**
35 | * 优先缓存,缓存用同步的方式保存
36 | */
37 | public static IStrategy firstCacheSync() {
38 | return new FirstCacheStrategy(true);
39 | }
40 |
41 | /**
42 | * 优先缓存,并设置超时时间
43 | * @param milliSecond 毫秒
44 | */
45 | public static IStrategy firstCacheTimeout(long milliSecond) {
46 | return new FirstCacheTimeoutStrategy(milliSecond);
47 | }
48 |
49 | /**
50 | * 优先缓存,并设置超时时间,缓存用同步的方式保存
51 | * @param milliSecond 毫秒
52 | */
53 | public static IStrategy firstCacheTimeoutSync(long milliSecond) {
54 | return new FirstCacheTimeoutStrategy(milliSecond,true);
55 | }
56 |
57 |
58 | /**
59 | * 仅加载网络,但数据依然会被缓存
60 | */
61 | public static IStrategy onlyRemote() {
62 | return new OnlyRemoteStrategy();
63 | }
64 |
65 | /**
66 | * 仅加载网络,但数据依然会被缓存
67 | */
68 | public static IStrategy onlyRemoteSync() {
69 | return new OnlyRemoteStrategy(true);
70 | }
71 |
72 | /**
73 | * 仅加载缓存
74 | */
75 | public static IStrategy onlyCache() {
76 | return new OnlyCacheStrategy();
77 | }
78 |
79 | /**
80 | * 先加载缓存,后加载网络,缓存用异步的方式保存
81 | */
82 | public static IStrategy cacheAndRemote() {
83 | return new CacheAndRemoteStrategy();
84 | }
85 |
86 | /**
87 | * 先加载缓存,后加载网络,缓存用同步的方式保存
88 | */
89 | public static IStrategy cacheAndRemoteSync() {
90 | return new CacheAndRemoteStrategy(true);
91 | }
92 |
93 | /**
94 | * 仅加载网络,不缓存
95 | */
96 | public static IStrategy none() {
97 | return NoneStrategy.INSTANCE;
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/FirstCacheStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 | import com.zchu.rxcache.CacheTarget;
4 | import com.zchu.rxcache.RxCache;
5 | import com.zchu.rxcache.RxCacheHelper;
6 | import com.zchu.rxcache.data.CacheResult;
7 |
8 | import org.reactivestreams.Publisher;
9 |
10 | import java.lang.reflect.Type;
11 |
12 | import io.reactivex.Flowable;
13 | import io.reactivex.Observable;
14 |
15 | /**
16 | * 优先缓存
17 | * 作者: 赵成柱 on 2016/9/12 0012.
18 | */
19 | public final class FirstCacheStrategy implements IStrategy {
20 | private boolean isSync;
21 |
22 | public FirstCacheStrategy() {
23 | isSync = false;
24 | }
25 |
26 | public FirstCacheStrategy(boolean isSync) {
27 | this.isSync = isSync;
28 | }
29 |
30 | @Override
31 | public Observable> execute(RxCache rxCache, String key, Observable source, Type type) {
32 | Observable> cache = RxCacheHelper.loadCache(rxCache, key, type,true);
33 | Observable> remote;
34 | if (isSync) {
35 | remote = RxCacheHelper.loadRemoteSync(rxCache, key, source, CacheTarget.MemoryAndDisk,false);
36 | } else {
37 | remote = RxCacheHelper.loadRemote(rxCache, key, source, CacheTarget.MemoryAndDisk,false);
38 | }
39 | return cache.switchIfEmpty(remote);
40 | }
41 |
42 | @Override
43 | public Publisher> flow(RxCache rxCache, String key, Flowable source, Type type) {
44 | Flowable> cache = RxCacheHelper.loadCacheFlowable(rxCache, key, type,true);
45 | Flowable> remote;
46 | if (isSync) {
47 | remote =RxCacheHelper.loadRemoteSyncFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk,false);
48 | } else {
49 | remote =RxCacheHelper.loadRemoteFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk,false);
50 | }
51 | return cache.switchIfEmpty(remote);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/FirstCacheTimeoutStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 | import com.zchu.rxcache.CacheTarget;
4 | import com.zchu.rxcache.RxCache;
5 | import com.zchu.rxcache.RxCacheHelper;
6 | import com.zchu.rxcache.data.CacheResult;
7 |
8 | import org.reactivestreams.Publisher;
9 |
10 | import java.lang.reflect.Type;
11 |
12 | import io.reactivex.Flowable;
13 | import io.reactivex.Observable;
14 | import io.reactivex.functions.Predicate;
15 |
16 | /**
17 | * 优先缓存并可设置超时时间
18 | * 作者: 赵成柱 on 2016/9/12 0012.
19 | */
20 | public final class FirstCacheTimeoutStrategy implements IStrategy {
21 | private boolean isSync;
22 | private long milliSecond;
23 |
24 | /**
25 | * @param milliSecond 毫秒数
26 | */
27 | public FirstCacheTimeoutStrategy(long milliSecond) {
28 | this(milliSecond, false);
29 | }
30 |
31 | /**
32 | * @param milliSecond 毫秒数
33 | * @param isSync 是否用同步的方式保存缓存
34 | */
35 | public FirstCacheTimeoutStrategy(long milliSecond, boolean isSync) {
36 | this.isSync = isSync;
37 | this.milliSecond = milliSecond;
38 | }
39 |
40 | @Override
41 | public Observable> execute(RxCache rxCache, String key, Observable source, Type type) {
42 | Observable> cache = RxCacheHelper.loadCache(rxCache, key, type, true);
43 | cache = cache.filter(new Predicate>() {
44 | @Override
45 | public boolean test(CacheResult tCacheResult) throws Exception {
46 | return System.currentTimeMillis() - tCacheResult.getTimestamp() <= milliSecond;
47 | }
48 | });
49 | Observable> remote;
50 | if (isSync) {
51 | remote = RxCacheHelper.loadRemoteSync(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
52 | } else {
53 | remote = RxCacheHelper.loadRemote(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
54 | }
55 | return cache.switchIfEmpty(remote);
56 | }
57 |
58 | @Override
59 | public Publisher> flow(RxCache rxCache, String key, Flowable source, Type type) {
60 | Flowable> cache = RxCacheHelper.loadCacheFlowable(rxCache, key, type, true);
61 | cache = cache.filter(new Predicate>() {
62 | @Override
63 | public boolean test(CacheResult tCacheResult) throws Exception {
64 | return System.currentTimeMillis() - tCacheResult.getTimestamp() <= milliSecond;
65 | }
66 | });
67 | Flowable> remote;
68 | if (isSync) {
69 | remote = RxCacheHelper.loadRemoteSyncFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
70 | } else {
71 | remote = RxCacheHelper.loadRemoteFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
72 | }
73 | return cache.switchIfEmpty(remote);
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/FirstRemoteStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 | import com.zchu.rxcache.CacheTarget;
4 | import com.zchu.rxcache.RxCache;
5 | import com.zchu.rxcache.RxCacheHelper;
6 | import com.zchu.rxcache.data.CacheResult;
7 |
8 | import org.reactivestreams.Publisher;
9 |
10 | import java.lang.reflect.Type;
11 | import java.util.Arrays;
12 |
13 | import io.reactivex.Flowable;
14 | import io.reactivex.Observable;
15 |
16 | /**
17 | * 优先网络
18 | * 作者: 赵成柱 on 2016/9/12 0012.
19 | */
20 | public final class FirstRemoteStrategy implements IStrategy {
21 | private boolean isSync;
22 |
23 | public FirstRemoteStrategy() {
24 | isSync = false;
25 | }
26 |
27 | public FirstRemoteStrategy(boolean isSync) {
28 | this.isSync = isSync;
29 | }
30 |
31 | @Override
32 | public Observable> execute(RxCache rxCache, String key, Observable source, Type type) {
33 | Observable> cache = RxCacheHelper.loadCache(rxCache, key, type, true);
34 | Observable> remote;
35 | if (isSync) {
36 | remote = RxCacheHelper.loadRemoteSync(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
37 | } else {
38 | remote = RxCacheHelper.loadRemote(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
39 | }
40 | return Observable
41 | .concatDelayError(Arrays.asList(remote,cache))
42 | .take(1);
43 | }
44 |
45 | @Override
46 | public Publisher> flow(RxCache rxCache, String key, Flowable source, Type type) {
47 | Flowable> cache = RxCacheHelper.loadCacheFlowable(rxCache, key, type, true);
48 | Flowable> remote;
49 | if (isSync) {
50 | remote = RxCacheHelper.loadRemoteSyncFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
51 | } else {
52 | remote =RxCacheHelper.loadRemoteFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
53 | }
54 | return Flowable
55 | .concatDelayError(Arrays.asList(remote,cache))
56 | .take(1);
57 | }
58 |
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/IFlowableStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 |
4 | import com.zchu.rxcache.RxCache;
5 | import com.zchu.rxcache.data.CacheResult;
6 |
7 | import org.reactivestreams.Publisher;
8 |
9 | import java.lang.reflect.Type;
10 |
11 | import io.reactivex.Flowable;
12 |
13 |
14 | /**
15 | * author : zchu
16 | * date : 2017/10/11
17 | * desc :
18 | */
19 | public interface IFlowableStrategy {
20 |
21 | Publisher> flow(RxCache rxCache, String key, Flowable source, Type type);
22 | }
23 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/IObservableStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 |
4 | import com.zchu.rxcache.RxCache;
5 | import com.zchu.rxcache.data.CacheResult;
6 |
7 | import java.lang.reflect.Type;
8 |
9 | import io.reactivex.Observable;
10 |
11 |
12 | /**
13 | * author : zchu
14 | * date : 2017/10/11
15 | * desc :
16 | */
17 | public interface IObservableStrategy {
18 |
19 | Observable> execute(RxCache rxCache, String key, Observable source, Type type);
20 | }
21 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/IStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 |
4 | /**
5 | * 作者: 赵成柱 on 2016/9/12 0012.
6 | */
7 | public interface IStrategy extends IObservableStrategy,IFlowableStrategy {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/NoneStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 | import com.zchu.rxcache.RxCache;
4 | import com.zchu.rxcache.data.CacheResult;
5 | import com.zchu.rxcache.data.ResultFrom;
6 |
7 | import org.reactivestreams.Publisher;
8 |
9 | import java.lang.reflect.Type;
10 |
11 | import io.reactivex.Flowable;
12 | import io.reactivex.Observable;
13 | import io.reactivex.annotations.NonNull;
14 | import io.reactivex.functions.Function;
15 |
16 |
17 | /**
18 | * Created by Chu on 2017/6/24.
19 | * 仅加载网络,不缓存
20 | */
21 |
22 | public final class NoneStrategy implements IStrategy {
23 |
24 | private NoneStrategy() {
25 | }
26 |
27 | static final NoneStrategy INSTANCE = new NoneStrategy();
28 |
29 | @Override
30 | public Observable> execute(RxCache rxCache, final String key, Observable source, Type type) {
31 | return source.map(new Function>() {
32 | @Override
33 | public CacheResult apply(@NonNull T t) throws Exception {
34 | return new CacheResult<>(ResultFrom.Remote, key, t);
35 | }
36 | });
37 | }
38 |
39 | @Override
40 | public Publisher> flow(RxCache rxCache, final String key, Flowable source, Type type) {
41 | return source.map(new Function>() {
42 | @Override
43 | public CacheResult apply(@NonNull T t) throws Exception {
44 | return new CacheResult<>(ResultFrom.Remote, key, t);
45 | }
46 | });
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/OnlyCacheStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 | import com.zchu.rxcache.RxCache;
4 | import com.zchu.rxcache.RxCacheHelper;
5 | import com.zchu.rxcache.data.CacheResult;
6 |
7 | import org.reactivestreams.Publisher;
8 |
9 | import java.lang.reflect.Type;
10 |
11 | import io.reactivex.Flowable;
12 | import io.reactivex.Observable;
13 |
14 |
15 | /**
16 | * 仅加载缓存
17 | * 作者: 赵成柱 on 2016/9/12 0012.
18 | */
19 | public final class OnlyCacheStrategy implements IStrategy {
20 |
21 | @Override
22 | public Observable> execute(RxCache rxCache, String key, Observable source, Type type) {
23 | return RxCacheHelper.loadCache(rxCache, key, type,false);
24 | }
25 |
26 | @Override
27 | public Publisher> flow(RxCache rxCache, String key, Flowable source, Type type) {
28 | return RxCacheHelper.loadCacheFlowable(rxCache, key, type,false);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/stategy/OnlyRemoteStrategy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.stategy;
2 |
3 | import com.zchu.rxcache.CacheTarget;
4 | import com.zchu.rxcache.RxCache;
5 | import com.zchu.rxcache.RxCacheHelper;
6 | import com.zchu.rxcache.data.CacheResult;
7 |
8 | import org.reactivestreams.Publisher;
9 |
10 | import java.lang.reflect.Type;
11 |
12 | import io.reactivex.Flowable;
13 | import io.reactivex.Observable;
14 |
15 |
16 | /**
17 | * 仅加载网络,但数据依然会被缓存
18 | * 作者: 赵成柱 on 2016/9/12 0012.
19 | */
20 | class OnlyRemoteStrategy implements IStrategy {
21 | private boolean isSync;
22 |
23 | public OnlyRemoteStrategy() {
24 | isSync = false;
25 | }
26 |
27 | public OnlyRemoteStrategy(boolean isSync) {
28 | this.isSync = isSync;
29 | }
30 |
31 | @Override
32 | public Observable> execute(RxCache rxCache, String key, Observable source, Type type) {
33 | if (isSync) {
34 | return RxCacheHelper.loadRemoteSync(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
35 | } else {
36 | return RxCacheHelper.loadRemote(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
37 | }
38 | }
39 |
40 | @Override
41 | public Publisher> flow(RxCache rxCache, String key, Flowable source, Type type) {
42 | if (isSync) {
43 | return RxCacheHelper.loadRemoteSyncFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
44 | } else {
45 | return RxCacheHelper.loadRemoteFlowable(rxCache, key, source, CacheTarget.MemoryAndDisk, false);
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/utils/LogUtils.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.utils;
2 |
3 | import android.util.Log;
4 |
5 | import java.util.Collection;
6 | import java.util.Iterator;
7 |
8 | public final class LogUtils {
9 | private LogUtils() {
10 | }
11 |
12 | public static boolean DEBUG =false;
13 |
14 | public static void log(Object message) {
15 | StackTraceElement element = new Throwable().getStackTrace()[1];
16 | print(element, message, null);
17 | }
18 | public static void log(Object message, Throwable error) {
19 | StackTraceElement element = new Throwable().getStackTrace()[1];
20 | print(element, message, error);
21 | }
22 |
23 | public static void debug(Object message) {
24 | if (DEBUG) {
25 | StackTraceElement element = new Throwable().getStackTrace()[1];
26 | print(element, message, null);
27 | }
28 | }
29 | public static void debug(Object message, Throwable error) {
30 | if (DEBUG) {
31 | StackTraceElement element = new Throwable().getStackTrace()[1];
32 | print(element, message, error);
33 | }
34 | }
35 |
36 |
37 |
38 | private static void print(StackTraceElement element, Object message, Throwable error) {
39 | String className = element.getClassName();
40 | className = className.substring(className.lastIndexOf('.') + 1);
41 | String tag = className+'.'+element.getMethodName()+'('+element.getFileName()+':'+element.getLineNumber()+')';
42 | String text = toString(message);
43 |
44 | if (error != null) {
45 | Log.e("[RxCache]", tag + "\n\t" + text, error);
46 | } else {
47 | Log.e("[RxCache]", tag + "\n\t" + text);
48 | }
49 | }
50 |
51 | private static String toString(Object message) {
52 | if (message == null) {
53 | return "[null]";
54 | }
55 | if (message instanceof Throwable) {
56 | return Log.getStackTraceString((Throwable) message);
57 | }
58 | if (message instanceof Collection) {
59 | return toString((Collection) message);
60 | }
61 | return String.valueOf(message);
62 | }
63 | private static String toString(Collection message) {
64 | Iterator it = message.iterator();
65 | if (! it.hasNext())
66 | return "[]";
67 |
68 | StringBuilder sb = new StringBuilder();
69 | sb.append('[');
70 | for (;;) {
71 | Object e = it.next();
72 | sb.append(e);
73 | if (! it.hasNext())
74 | return sb.append(']').toString();
75 | sb.append(",\n ");
76 | }
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/utils/MemorySizeOf.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.utils;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | import java.io.ByteArrayOutputStream;
6 | import java.io.IOException;
7 | import java.io.ObjectOutputStream;
8 | import java.io.Serializable;
9 |
10 |
11 | /**
12 | * Implements functions useful to check
13 | * MemorySizeOf usage.
14 | *
15 | * @author Pierre Malarme
16 | * @version 1.0
17 | */
18 | public class MemorySizeOf {
19 |
20 | /**
21 | * Function that get the size of an object.
22 | *
23 | * @return Size in bytes of the object or -1 if the object
24 | * is null.
25 | */
26 | public static int sizeOf(Serializable serial) throws IOException {
27 | if (serial == null) {
28 | return 0;
29 | }
30 | int size;
31 | ByteArrayOutputStream baos = null;
32 | ObjectOutputStream oos = null;
33 | try {
34 | baos = new ByteArrayOutputStream();
35 | oos = new ObjectOutputStream(baos);
36 | oos.writeObject(serial);
37 | oos.flush(); //缓冲流
38 | size = baos.size();
39 | } finally {
40 | Utils.close(oos);
41 | Utils.close(baos);
42 | }
43 | return size;
44 | }
45 |
46 |
47 | public static int sizeOf(Bitmap bitmap) {
48 | if (bitmap == null) {
49 | return 0;
50 | }
51 |
52 | int size;
53 | ByteArrayOutputStream baos = null;
54 | try {
55 | baos = new ByteArrayOutputStream();
56 | bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
57 | size = baos.size();
58 | } finally {
59 | Utils.close(baos);
60 | }
61 | return size;
62 | }
63 |
64 | }
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/utils/Occupy.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.utils;
2 |
3 | import java.lang.reflect.Field;
4 | import java.lang.reflect.Modifier;
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by Chu on 2017/6/1.
10 | */
11 |
12 | public class Occupy {
13 | //这8个方法不写不行,否则occupyof(int x)会自动重载到occupyof(Object o),并且无法在方法中判断
14 | public static int occupyof(boolean variable) {
15 | return 1;
16 | }
17 |
18 | public static int occupyof(byte variable) {
19 | return 1;
20 | }
21 |
22 | public static int occupyof(short variable) {
23 | return 2;
24 | }
25 |
26 | public static int occupyof(char variable) {
27 | return 2;
28 | }
29 |
30 | public static int occupyof(int variable) {
31 | return 4;
32 | }
33 |
34 | public static int occupyof(float variable) {
35 | return 4;
36 | }
37 |
38 | public static int occupyof(long variable) {
39 | return 8;
40 | }
41 |
42 | public static int occupyof(double variable) {
43 | return 8;
44 | }
45 |
46 | public Occupy(byte nullReferenceSize, byte emptyObjectSize, byte emptyArrayVarSize) {
47 | this.NULL_REFERENCE_SIZE = nullReferenceSize;
48 | this.EMPTY_OBJECT_SIZE = emptyObjectSize;
49 | this.EMPTY_ARRAY_VAR_SIZE = emptyArrayVarSize;
50 | }
51 |
52 | public static Occupy forJRockitVM() {
53 | return new Occupy((byte) 4, (byte) 8, (byte) 8);
54 | }
55 |
56 | public static Occupy forSun32BitsVM() {
57 | return new Occupy((byte) 4, (byte) 8, (byte) 4);
58 | }
59 |
60 | public static Occupy forSun64BitsVM() {
61 | return new Occupy((byte) 8, (byte) 16, (byte) 8);
62 | }
63 |
64 | public static Occupy forDetectedVM(){
65 | return null;
66 | }
67 |
68 | private final byte NULL_REFERENCE_SIZE;
69 | private final byte EMPTY_OBJECT_SIZE;
70 | private final byte EMPTY_ARRAY_VAR_SIZE;
71 |
72 | private static class ref{
73 | public ref(Object obj){
74 | this.obj = obj;
75 | }
76 | final Object obj;
77 | @Override
78 | public boolean equals(Object obj) {
79 | return (obj instanceof ref) && ((ref)obj).obj == this.obj;
80 | }
81 | @Override
82 | public int hashCode() {
83 | return obj.hashCode();
84 | }
85 | }
86 |
87 | private List dedup = new ArrayList();
88 |
89 | public int occupyof(Object object){
90 | dedup.clear();
91 | return occupyof0(object);
92 | }
93 | private int occupyof0(Object object) {
94 | if (object == null)
95 | return 0;
96 | ref r = new ref(object);
97 | if(dedup.contains(r))
98 | return 0;
99 | dedup.add(r);
100 | int varSize = 0;//对象中的值类型、引用类型变量大小
101 | int objSize = 0;//对象中的引用类型指向的对象实例的大小
102 | for (Class clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
103 | // System.out.println(clazz);
104 | if (clazz.isArray()) {//当前对象的数组
105 | varSize += EMPTY_ARRAY_VAR_SIZE;
106 | Class> componentType = clazz.getComponentType();
107 | if (componentType.isPrimitive()) {//当前数组是原生类型的数组
108 | varSize += lengthOfPrimitiveArray(object) * sizeofPrimitiveClass(componentType);
109 | return occupyOfSize(EMPTY_OBJECT_SIZE, varSize, 0);
110 | }
111 | Object[] array = (Object[]) object;
112 | varSize += NULL_REFERENCE_SIZE * array.length;//当前数组有length个引用,每个占用4字节
113 | for (Object o : array)
114 | objSize += occupyof0(o);
115 | return occupyOfSize(EMPTY_OBJECT_SIZE, varSize, objSize);
116 | }
117 | Field[] fields = clazz.getDeclaredFields();
118 | for (Field field : fields) {
119 | if (Modifier.isStatic(field.getModifiers()))
120 | continue;//类成员不计
121 | //System.out.println(field.getDeclaringClass());
122 | if(clazz != field.getDeclaringClass())
123 | continue;
124 | Class> type = field.getType();
125 | if (type.isPrimitive())
126 | varSize += sizeofPrimitiveClass(type);
127 | else {
128 | varSize += NULL_REFERENCE_SIZE;//一个引用型变量占用4个字节
129 | try {
130 | field.setAccessible(true);//可以访问非public类型的变量
131 | objSize += occupyof0(field.get(object));
132 | } catch (Exception e) {
133 | objSize += occupyofConstructor(object, field);
134 | }
135 | }
136 | }
137 | }
138 | return occupyOfSize(EMPTY_OBJECT_SIZE, varSize, objSize);
139 | }
140 |
141 | public static int sizeof(boolean variable) {
142 | return 1;
143 | }
144 |
145 | public static int sizeof(byte variable) {
146 | return 1;
147 | }
148 |
149 | public static int sizeof(short variable) {
150 | return 2;
151 | }
152 |
153 | public static int sizeof(char variable) {
154 | return 2;
155 | }
156 |
157 | public static int sizeof(int variable) {
158 | return 4;
159 | }
160 |
161 | public static int sizeof(float variable) {
162 | return 4;
163 | }
164 |
165 | public static int sizeof(long variable) {
166 | return 8;
167 | }
168 |
169 | public static int sizeof(double variable) {
170 | return 8;
171 | }
172 |
173 |
174 | public int sizeof(Object object) {
175 | if (object == null)
176 | return 0;
177 | int size = EMPTY_OBJECT_SIZE;
178 | Class clazz = object.getClass();
179 | if (clazz.isArray()) {
180 | size += EMPTY_ARRAY_VAR_SIZE;//length变量是int型
181 | Class> componentType = clazz.getComponentType();
182 | if (componentType.isPrimitive())
183 | return size + lengthOfPrimitiveArray(object) * sizeofPrimitiveClass(componentType);
184 | Object[] array = (Object[]) object;
185 | size += 4 * array.length;
186 | for (Object o : array)
187 | size += sizeof(o);
188 | return size;
189 | }
190 | Field[] fields = clazz.getDeclaredFields();
191 | for (Field field : fields) {
192 | if (Modifier.isStatic(field.getModifiers()))
193 | continue;//类成员不计
194 | Class> type = field.getType();
195 | if (type.isPrimitive())
196 | size += sizeofPrimitiveClass(type);
197 | else {
198 | size += 4;//一个引用型变量占用4个字节
199 | try {
200 | field.setAccessible(true);//可以访问非public类型的变量
201 | size += sizeof(field.get(object));
202 | } catch (Exception e) {
203 | size += sizeofConstructor(object, field);
204 | }
205 | }
206 | }
207 | return size;
208 | }
209 |
210 | private static int occupyofConstructor(Object object, Field field) {
211 | throw new UnsupportedOperationException("field type Constructor not accessible: " + object.getClass() + " field:" + field);
212 | }
213 |
214 | private static int sizeofConstructor(Object object, Field field) {
215 | throw new UnsupportedOperationException("field type Constructor not accessible: " + object.getClass() + " field:" + field);
216 | }
217 |
218 |
219 | private static int occupyOfSize(int size) {
220 | return (size + 7) / 8 * 8;
221 | }
222 |
223 | private static int occupyOfSize(int selfSize, int varsSize, int objsSize) {
224 | // System.out.println("self=" + selfSize + " vars=" + varsSize + " objs=" + objsSize);
225 | return occupyOfSize(selfSize) + occupyOfSize(varsSize) + objsSize;
226 | }
227 |
228 | private static int sizeofPrimitiveClass(Class clazz) {
229 | return clazz == boolean.class || clazz == byte.class ? 1 : clazz == char.class || clazz == short.class ? 2 : clazz == int.class || clazz == float.class ? 4
230 | : 8;
231 | }
232 |
233 | private static int lengthOfPrimitiveArray(Object object) {
234 | Class> clazz = object.getClass();
235 | return clazz == boolean[].class ? ((boolean[]) object).length : clazz == byte[].class ? ((byte[]) object).length
236 | : clazz == char[].class ? ((char[]) object).length : clazz == short[].class ? ((short[]) object).length
237 | : clazz == int[].class ? ((int[]) object).length : clazz == float[].class ? ((float[]) object).length
238 | : clazz == long[].class ? ((long[]) object).length : ((double[]) object).length;
239 | }
240 | }
241 |
--------------------------------------------------------------------------------
/rxcache/src/main/java/com/zchu/rxcache/utils/Utils.java:
--------------------------------------------------------------------------------
1 | package com.zchu.rxcache.utils;
2 |
3 | import java.io.Closeable;
4 | import java.io.IOException;
5 |
6 |
7 | /**
8 | * 工具类
9 | */
10 | public final class Utils {
11 |
12 | private Utils() {
13 | }
14 |
15 | public static void close(Closeable close) {
16 | if (close != null) {
17 | try {
18 | closeThrowException(close);
19 | } catch (IOException ignored) {
20 | }
21 | }
22 | }
23 |
24 | public static void closeThrowException(Closeable close) throws IOException {
25 | if (close != null) {
26 | close.close();
27 | }
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/sample-debug.apk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/z-chu/RxCache/f8ce1751508f1684ff68eb770e90f5f3208e30fd/sample-debug.apk
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | android {
4 | compileSdkVersion 28
5 |
6 | defaultConfig {
7 | applicationId "com.zchu.sample"
8 | minSdkVersion 14
9 | targetSdkVersion 28
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | lintOptions {
23 | abortOnError false
24 | }
25 |
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(include: ['*.jar'], dir: 'libs')
30 | androidTestImplementation('androidx.test.espresso:espresso-core:3.1.1', {
31 | exclude group: 'com.android.support', module: 'support-annotations'
32 | })
33 | implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
34 | testImplementation 'junit:junit:4.12'
35 | implementation 'com.squareup.retrofit2:retrofit:2.5.0'
36 | implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
37 | implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
38 | implementation 'io.reactivex.rxjava2:rxjava:2.2.0'
39 | implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
40 | implementation 'com.squareup.okio:okio:1.15.0'
41 | implementation 'com.squareup.okhttp3:okhttp:3.12.0'
42 | implementation 'com.zchu:zlog:1.0.1'
43 |
44 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
45 | implementation project(':rxcache')
46 | implementation project(':rxcache-kotlin')
47 | }
48 | repositories {
49 | mavenCentral()
50 | }
51 |
--------------------------------------------------------------------------------
/sample/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 E:\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 |
--------------------------------------------------------------------------------
/sample/src/androidTest/java/com/zchu/sample/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.zchu.sample;
2 |
3 | import android.content.Context;
4 |
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 |
8 | import androidx.test.InstrumentationRegistry;
9 | import androidx.test.runner.AndroidJUnit4;
10 |
11 | import static org.junit.Assert.assertEquals;
12 |
13 | /**
14 | * Instrumentation test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() throws Exception {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getTargetContext();
24 |
25 | assertEquals("com.zchu.sample", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/zchu/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.zchu.sample
2 |
3 | import android.os.Bundle
4 | import android.view.View
5 | import android.widget.Switch
6 | import android.widget.TextView
7 | import android.widget.Toast
8 | import androidx.annotation.IdRes
9 | import androidx.appcompat.app.AppCompatActivity
10 | import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
11 | import com.zchu.log.Logger
12 | import com.zchu.rxcache.RxCache
13 | import com.zchu.rxcache.data.CacheResult
14 | import com.zchu.rxcache.data.ResultFrom
15 | import com.zchu.rxcache.diskconverter.GsonDiskConverter
16 | import com.zchu.rxcache.kotlin.load
17 | import com.zchu.rxcache.kotlin.rxCache
18 | import com.zchu.rxcache.stategy.CacheStrategy
19 | import com.zchu.rxcache.stategy.IStrategy
20 | import io.reactivex.Observer
21 | import io.reactivex.android.schedulers.AndroidSchedulers
22 | import io.reactivex.disposables.Disposable
23 | import io.reactivex.schedulers.Schedulers
24 | import okhttp3.OkHttpClient
25 | import retrofit2.Retrofit
26 | import retrofit2.converter.gson.GsonConverterFactory
27 | import java.io.File
28 | import java.text.SimpleDateFormat
29 | import java.util.*
30 |
31 | class MainActivity : AppCompatActivity(), View.OnClickListener {
32 | private var serverAPI: ServerAPI? = null
33 | private var tvData: TextView? = null
34 | private var mSubscription: Disposable? = null
35 | private var swIsAsync: Switch? = null
36 |
37 |
38 | override fun onCreate(savedInstanceState: Bundle?) {
39 | super.onCreate(savedInstanceState)
40 | setContentView(R.layout.activity_main)
41 | tvData = findViewById(R.id.tv_data)
42 | swIsAsync = findViewById(R.id.sw_is_async)
43 | bindOnClickLister(
44 | R.id.btn_first_remote,
45 | R.id.btn_first_cache,
46 | R.id.btn_first_cache_timeout,
47 | R.id.btn_only_remote,
48 | R.id.btn_only_cache,
49 | R.id.btn_cache_and_remote,
50 | R.id.btn_none,
51 | R.id.btn_clean_cache,
52 | R.id.btn_load_cache,
53 | R.id.btn_save_cache
54 | )
55 | serverAPI = Retrofit.Builder()
56 | .baseUrl(ServerAPI.BASE_URL)
57 | .addConverterFactory(GsonConverterFactory.create())
58 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
59 | .client(OkHttpClient.Builder().build())
60 | .build()
61 | .create(ServerAPI::class.java)
62 | RxCache.initializeDefault(RxCache.Builder()
63 | .appVersion(2)
64 | .diskDir(File(cacheDir.path + File.separator + "data-cache"))
65 | .diskConverter(GsonDiskConverter())
66 | .diskMax((20 * 1024 * 1024).toLong())
67 | .memoryMax(0)
68 | .setDebug(true)
69 | .build())
70 | Logger.init("RxCache")
71 | }
72 |
73 | fun bindOnClickLister(@IdRes vararg ids: Int) {
74 | for (id in ids) {
75 | val view = findViewById(id)
76 | view?.setOnClickListener(this)
77 | }
78 | }
79 |
80 | override fun onClick(view: View) {
81 | when (view.id) {
82 | R.id.btn_first_remote ->
83 | if (swIsAsync!!.isChecked) {
84 | loadData(CacheStrategy.firstRemote())
85 | } else {
86 | loadData(CacheStrategy.firstRemoteSync())
87 | }
88 | R.id.btn_first_cache ->
89 | if (swIsAsync!!.isChecked) {
90 | loadData(CacheStrategy.firstCache())
91 | } else {
92 | loadData(CacheStrategy.firstCacheSync())
93 | }
94 | R.id.btn_first_cache_timeout ->
95 | if (swIsAsync!!.isChecked) {
96 | loadData(CacheStrategy.firstCacheTimeout(5000))
97 | } else {
98 | loadData(CacheStrategy.firstCacheTimeoutSync(5000))
99 | }
100 | R.id.btn_only_remote ->
101 | if (swIsAsync!!.isChecked) {
102 | loadData(CacheStrategy.onlyRemote())
103 | } else {
104 | loadData(CacheStrategy.onlyRemoteSync())
105 | }
106 | R.id.btn_only_cache ->
107 | loadData(CacheStrategy.onlyCache())
108 | R.id.btn_cache_and_remote ->
109 | if (swIsAsync!!.isChecked) {
110 | loadData(CacheStrategy.cacheAndRemote())
111 | } else {
112 | loadData(CacheStrategy.cacheAndRemoteSync())
113 | }
114 | R.id.btn_none ->
115 | loadData(CacheStrategy.none())
116 | R.id.btn_load_cache ->
117 | RxCache.getDefault()
118 | .load>("custom_key")
119 | .subscribe(object : Observer>> {
120 | override fun onSubscribe(disposable: Disposable) {
121 | mSubscription = disposable
122 | }
123 |
124 | override fun onNext(listCacheResult: CacheResult>) {
125 | Logger.e(listCacheResult)
126 | val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
127 | .format(Date(listCacheResult.timestamp))
128 | tvData!!.text = "来自缓存 写入时间:" + format + "\n " + listCacheResult.data
129 | }
130 |
131 | override fun onError(throwable: Throwable) {
132 | tvData!!.text = throwable.message
133 | }
134 |
135 | override fun onComplete() {
136 |
137 | }
138 | })
139 |
140 | R.id.btn_save_cache -> {
141 | val subjectsBean = Movie.SubjectsBean()
142 | subjectsBean.year = "测试数据:sava-year"
143 | subjectsBean.title = "测试数据:sava-title"
144 | RxCache.getDefault().save("custom_key", Arrays.asList(subjectsBean))
145 | ?.subscribe()
146 |
147 | Toast.makeText(this,"已写入测试数据",Toast.LENGTH_SHORT).show()
148 | }
149 | R.id.btn_clean_cache -> {
150 | RxCache.getDefault().clear().subscribe()
151 | tvData!!.text = "数据"
152 | }
153 | }
154 |
155 |
156 | }
157 |
158 | private fun loadData(strategy: IStrategy) {
159 | if (mSubscription != null && !mSubscription!!.isDisposed) {
160 | mSubscription!!.dispose()
161 | }
162 | tvData!!.text = "加载中..."
163 | val startTime = System.currentTimeMillis()
164 | serverAPI!!.inTheatersMovies
165 | .map { it.subjects!! }
166 | //泛型这样使用
167 | .rxCache("custom_key", strategy)
168 | .subscribeOn(Schedulers.io())
169 | .observeOn(AndroidSchedulers.mainThread())
170 | .subscribe(object : Observer>> {
171 | override fun onSubscribe(disposable: Disposable) {
172 | mSubscription = disposable
173 | }
174 |
175 | override fun onNext(listCacheResult: CacheResult>) {
176 | Logger.e(listCacheResult)
177 | if (ResultFrom.ifFromCache(listCacheResult.from)) {
178 | val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
179 | .format(Date(listCacheResult.timestamp))
180 | tvData!!.text = "来自缓存 写入时间:" + format + "\n " + listCacheResult.data
181 | } else {
182 | tvData!!.text = "来自网络:\n " + listCacheResult.data + "\n 响应时间:" + (System.currentTimeMillis() - startTime) + "毫秒"
183 | }
184 | }
185 |
186 | override fun onError(throwable: Throwable) {
187 | tvData!!.text = throwable.message
188 | }
189 |
190 | override fun onComplete() {
191 |
192 | }
193 | })
194 | }
195 |
196 | companion object {
197 | private val TAG = "MainActivity"
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/zchu/sample/Movie.kt:
--------------------------------------------------------------------------------
1 | package com.zchu.sample
2 |
3 | class Movie {
4 |
5 |
6 | var count: Int = 0
7 | var start: Int = 0
8 | var title: String? = null
9 | var total: Int = 0
10 | var subjects: List? = null
11 |
12 | class SubjectsBean {
13 |
14 | var alt: String? = null
15 | var collect_count: Int = 0
16 | var id: String? = null
17 | var images: ImagesBean? = null
18 | var original_title: String? = null
19 | var rating: RatingBean? = null
20 | var subtype: String? = null
21 | var title: String? = null
22 | var year: String? = null
23 | var casts: List? = null
24 | var directors: List? = null
25 | var genres: List? = null
26 |
27 |
28 | override fun toString(): String {
29 | return "title='" + title + '\''.toString() +
30 | ", year='" + year + '\''.toString()
31 | }
32 |
33 | class ImagesBean {
34 | var large: String? = null
35 | var medium: String? = null
36 | var small: String? = null
37 | }
38 |
39 | class RatingBean {
40 |
41 | var average: Double = 0.toDouble()
42 | var max: Int = 0
43 | var min: Int = 0
44 | var stars: String? = null
45 | }
46 |
47 | class CastsBean {
48 |
49 | var alt: String? = null
50 | var avatars: AvatarsBean? = null
51 | var id: String? = null
52 | var name: String? = null
53 |
54 |
55 | }
56 |
57 | class AvatarsBean {
58 |
59 |
60 | var large: String? = null
61 | var medium: String? = null
62 | var small: String? = null
63 | }
64 |
65 | class DirectorsBean {
66 |
67 | var alt: String? = null
68 | var avatars: AvatarsBeanX? = null
69 | var id: String? = null
70 | var name: String? = null
71 |
72 |
73 | }
74 |
75 | class AvatarsBeanX {
76 |
77 | var large: String? = null
78 | var medium: String? = null
79 | var small: String? = null
80 | }
81 | }
82 |
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/zchu/sample/ServerAPI.java:
--------------------------------------------------------------------------------
1 | package com.zchu.sample;
2 |
3 |
4 | import io.reactivex.Observable;
5 | import retrofit2.http.GET;
6 |
7 | public interface ServerAPI {
8 | String BASE_URL = "https://api.douban.com";
9 |
10 | @GET("/v2/movie/in_theaters?city=上海")
11 | Observable getInTheatersMovies();
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |