├── .gitignore
├── LICENSE
├── README.md
├── README_CN.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── chiclaim
│ │ └── rxjava
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── chiclaim
│ │ │ └── rxjava
│ │ │ ├── BaseFragment.java
│ │ │ ├── MainActivity.java
│ │ │ ├── MainFragment.java
│ │ │ ├── MyApplication.java
│ │ │ ├── UseRxJavaRightWayActivity.java
│ │ │ ├── api
│ │ │ ├── ApiServiceFactory.java
│ │ │ ├── NetErrorType.java
│ │ │ ├── SearchApi.java
│ │ │ └── UserApi.java
│ │ │ ├── exception
│ │ │ ├── AccessDenyException.java
│ │ │ ├── ConversionException.java
│ │ │ ├── NetworkException.java
│ │ │ ├── Non200HttpException.java
│ │ │ └── UnKnowException.java
│ │ │ ├── model
│ │ │ ├── AuthToken.java
│ │ │ └── User.java
│ │ │ └── operator
│ │ │ ├── CheckCacheFragment.java
│ │ │ ├── CombineLatestFragment.java
│ │ │ ├── HttpWithTokenFragment.java
│ │ │ ├── ObservableDependencyFragment.java
│ │ │ ├── RetryWithDelay.java
│ │ │ ├── SearchDebounceFragment.java
│ │ │ ├── TryWhenFragment.java
│ │ │ ├── create
│ │ │ └── CreateOperatorFragment.java
│ │ │ └── transform
│ │ │ ├── ConcatFlatMapFragment.java
│ │ │ ├── FlatMapOperatorFragment.java
│ │ │ └── MapOperatorFragment.java
│ └── res
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── activity_use_rxjava_right_way.xml
│ │ ├── fragment_check_data.xml
│ │ ├── fragment_combine_latest.xml
│ │ ├── fragment_concat_flat_map_layout.xml
│ │ ├── fragment_container.xml
│ │ ├── fragment_create_operator.xml
│ │ ├── fragment_flatmap_operator.xml
│ │ ├── fragment_http_token.xml
│ │ ├── fragment_main.xml
│ │ ├── fragment_map_operator.xml
│ │ ├── fragment_observable_dependency.xml
│ │ ├── fragment_retry_when.xml
│ │ └── fragment_search.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
│ └── chiclaim
│ └── rxjava
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 |
15 | # Gradle files
16 | .gradle/
17 | build/
18 |
19 | # Local configuration file (sdk path, etc)
20 | local.properties
21 |
22 | # Proguard folder generated by Eclipse
23 | proguard/
24 |
25 | # Log Files
26 | *.log
27 |
28 | # Android Studio Navigation editor temp files
29 | .navigation/
30 |
31 | # Android Studio captures folder
32 | captures/
33 |
34 | .idea/
35 | *.iml
36 |
--------------------------------------------------------------------------------
/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 | # Deprecated
2 | 停止维护,已经迁移到 [AndroidAll](https://github.com/chiclaim/AndroidAll)
3 |
4 |
5 | ---
6 |
7 | > RxJava 系列文章
8 |
9 | [《一、RxJava create操作符的用法和源码分析》](http://blog.csdn.net/johnny901114/article/details/51524470)
10 |
11 | [《二、RxJava map操作符用法详解》](http://blog.csdn.net/johnny901114/article/details/51531348)
12 |
13 | [《三、RxJava flatMap操作符用法详解》](http://blog.csdn.net/johnny901114/article/details/51532776)
14 |
15 | [《四、RxJava concatMap操作符用法详解》](http://blog.csdn.net/johnny901114/article/details/51533282)
16 |
17 | [《五、RxJava onErrorResumeNext操作符实现app与服务器间token机制》](http://blog.csdn.net/johnny901114/article/details/51533586)
18 |
19 | [《六、RxJava retryWhen操作符实现错误重试机制》](http://blog.csdn.net/johnny901114/article/details/51539708)
20 |
21 | [《七、RxJava 使用debounce操作符 优化app搜索功能》](http://blog.csdn.net/johnny901114/article/details/51555203)
22 |
23 | [《八、RxJava concat操作处理多数据源》](http://blog.csdn.net/johnny901114/article/details/51568562)
24 |
25 | [《九、RxJava zip操作符在Android中的实际使用场景》](http://blog.csdn.net/johnny901114/article/details/51614927)
26 |
27 | [《十、switchIfEmpty操作符实现Android检查本地缓存逻辑判断》](http://blog.csdn.net/johnny901114/article/details/52585912)
28 |
29 | [《十一、defer操作符实现代码支持链式调用》](http://blog.csdn.net/johnny901114/article/details/51614927)
30 |
31 | [《十二、combineLatest操作符的高级使用》](http://blog.csdn.net/johnny901114/article/details/61191723)
32 |
33 | [《十三、RxJava导致Fragment Activity内存泄漏问题》](http://blog.csdn.net/johnny901114/article/details/67640594)
34 |
35 |
36 |
--------------------------------------------------------------------------------
/README_CN.md:
--------------------------------------------------------------------------------
1 | ## [READ English document](https://github.com/chiclaim/awesome_android_rxjava/blob/master/README.md)
2 |
3 | ## 在Android开发中的一些真实场景如何使用RxJava
4 |
5 | 该项目介绍了Rxjava一些常用的操作符和在实际场景使用的一些案例.
6 | 为了更加贴近真实项目, 项目中使用的网络请求和一些耗时任务都是请求本地服务器的. 服务器端使用Java web+Tomcat来实现的.
7 | 如果需要可以把服务器部署在你的本地机器上, 下载地址[下载地址](https://github.com/chiclaim/android_mvvm_server)
8 |
9 | ##Example Details
10 |
11 | ### 1. 基础部分
12 |
13 | 基础部分介绍了 Rxjava的一些常用操作符如:`create` 、`just` 、 `from` 、`map`、`flatMap`、`concatMap vs flatMap`
14 |
15 |
16 | ### 2. 每个HTTP请求都带token给服务器 [如果token过期则获取新token]
17 | 一般请情况下,很多公司的提api接口, 请求的的时候都需要带有token, 该token在用户第一次启动app或者登陆的时候去获取. 以后的所有请求都需要带该Token
18 | 如果token过期, 服务器将返回401, 这时候就需要去请求获取token的接口, 如果获取成功接着在请求原来的接口.
19 | 这个时候就两个回调的嵌套了. 实现起来比较费劲, 而且也不够优雅. 代码的可维护性变得很差.
20 | 可以使用 `onErrorResumeNext` 来处理这样的业务逻辑.
21 |
22 |
23 |
24 | ### 3. 搜索防抖[Search debounce]
25 |
26 | 现在几乎所有的App都有搜索功能 , 一般情况我们监听EditText控件,当值发生改变去请求搜索接口. 这将导致2个问题:
27 |
28 | * 可能导致很多没有意义的请求,耗费用户流量(因为控件的值没更改一次立即就会去请求网络)
29 |
30 | * 可能导致最终的结果不是用户想要的. 例如,用户一开始输入关键字'AB' 这个时候出现两个请求, 一个请求是A关键字, 一个请求是AB关键字.
31 | 表面上是'A'请求先发出去, 'AB'请求后发出去. 如果后发出去的'AB'请求先返回, 'A'请求后返回,那么'A'请求后的结果将会覆盖'AB'请求的结果.
32 | 从而导致搜索结果不正确.
33 |
34 | 很多文章说使用 `debounce` 操作可以解决这个问题.
35 | 但是, RxJava也不能完全解决这个问题, 可以使用 `debounce` 操作符 也只能从一定程度上减少这种情况的出现.
36 | 比如: 一开始用户输入了AB两个字符, 在某个时间段内, 用户没有输入新的关键字, 将会发出搜索请求, 此时用户又输入新的关键字C,
37 | 那就输入框就是ABC了, 在某个时间段内, 用户没有输入新的关键字, 将会发出搜索新的请求. 如果'ABC'的请求返回比'AB'的快, 那么AB请求的结果将会覆盖'ABC'请求的结果,从而导致不正确的结果
38 |
39 |
40 | ### 4. Observable is dependent on another Observable's result
41 | 例如, 在我的实际项目中上传图片到又拍云 需要先获取上传的url, 然后在上传图片. 所以上传图片这个任务需要依赖获取url这个任务
42 |
43 |
44 | ### 5. 检查数据缓存
45 | 比如获取列表数据, 如果数据库里有使用数据库的, 没有再去请求网络.
46 | 当然也可以应用到其他场景, 比如有多个数据源, 数据源有优先级, 哪个有数据就使用哪个.
47 |
48 | ### 6. HTTP 请求重试
49 |
50 | 当请求网络的时候出现错误, 我们需要重试, 如果不停的重试也没有多大意义, 出现错误延迟多少秒然后重试.
51 | 所以使用RxJava可以设置最多重试次数和延迟的时间.
52 |
53 | ### 7. 如何在Android中正确的使用RxJava
54 | 如何避免在Activity/Fragment内存泄露.
55 |
56 |
57 | ## Reference documents
58 |
59 | 1. [danlew posts](http://blog.danlew.net/page/6/)
60 | 2. [jianshu posts](http://www.jianshu.com/p/33c548bce571)
61 | 3. [myexception posts](http://www.myexception.cn/android/1949467.html)
62 | 4. [stackoverflow posts](http://stackoverflow.com/questions/26201420/retrofit-with-rxjava-handling-network-exceptions-globally)
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion '25.0.0'
6 |
7 | defaultConfig {
8 | applicationId "com.chiclaim.rxjava"
9 | minSdkVersion 15
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | compile fileTree(dir: 'libs', include: ['*.jar'])
25 | testCompile 'junit:junit:4.12'
26 |
27 | // Because RxAndroid releases are few and far between, it is recommended you also
28 | // explicitly depend on RxJava's latest version for bug fixes and new features.
29 |
30 | //image utils
31 |
32 |
33 | debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
34 | releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
35 | testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
36 |
37 | compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
38 |
39 | compile 'com.android.support:appcompat-v7:23.2.1'
40 | compile 'com.android.support:recyclerview-v7:23.2.1'
41 | compile 'com.android.support:support-annotations:23.2.1'
42 | compile 'io.reactivex:rxandroid:1.1.0'
43 | compile 'io.reactivex:rxjava:1.1.2'
44 | compile 'com.squareup.retrofit:retrofit:1.9.0'
45 | compile 'com.squareup.retrofit:retrofit-converters:1.9.0'
46 | compile 'com.squareup.okhttp3:okhttp:3.0.1'
47 | compile 'com.squareup.okhttp3:okhttp-urlconnection:3.0.1'
48 | compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
49 | compile 'com.squareup.picasso:picasso:2.5.2'
50 | compile 'com.android.support:design:23.2.1'
51 | }
52 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/yuzhiqiang/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/chiclaim/rxjava/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/BaseFragment.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.support.v4.app.Fragment;
6 | import android.util.Log;
7 | import android.view.View;
8 | import android.widget.TextView;
9 |
10 | /**
11 | * Created by chiclaim on 2016/01/27
12 | */
13 | public class BaseFragment extends Fragment implements View.OnClickListener {
14 |
15 | protected void printLog(TextView textView, String prefix, String s) {
16 | String content = prefix + "'" + s + "'" + "\nMain Thread:" + (getActivity().getMainLooper() == Looper.myLooper()) +
17 | ", Thread Name:" + Thread.currentThread().getName();
18 | Log.d("OnSubscribe", content);
19 | //if (!TextUtils.isEmpty(s)) {
20 | appendText(textView, content);
21 | //}
22 | }
23 |
24 | protected void printErrorLog(TextView textView, String prefix, String s) {
25 | String content = prefix + " Main Thread:" + (getActivity().getMainLooper() == Looper.myLooper()) +
26 | " thread name:" + Thread.currentThread().getName() + ",data:" + s;
27 | Log.e("OnSubscribe", content);
28 | //if (!TextUtils.isEmpty(s)) {
29 | appendText(textView, content);
30 | // }
31 | }
32 |
33 | protected void appendText(final TextView textView, final String content) {
34 | new Handler(Looper.getMainLooper()).post(new Runnable() {
35 | @Override
36 | public void run() {
37 | textView.append("\n\n");
38 | textView.append(content);
39 | }
40 | });
41 | }
42 |
43 |
44 | public final void addFragment(Fragment fragment) {
45 | String tag = getActivity().getClass().toString();
46 | getActivity().getSupportFragmentManager()
47 | .beginTransaction()
48 | .addToBackStack(tag)
49 | .replace(android.R.id.content, fragment, tag)
50 | .commit();
51 | }
52 |
53 |
54 | protected boolean isMain() {
55 | return Looper.myLooper() == Looper.getMainLooper();
56 | }
57 |
58 | protected String getMainText(String flag) {
59 | return flag + " is main thread : " + (Looper.myLooper() == Looper.getMainLooper());
60 |
61 | }
62 |
63 | @Override
64 | public void onClick(View v) {
65 |
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava;
2 |
3 | import android.os.Bundle;
4 | import android.support.v4.app.FragmentTransaction;
5 | import android.support.v7.app.ActionBar;
6 | import android.support.v7.app.AppCompatActivity;
7 |
8 | /**
9 | * Created by chiclaim on 2016/03/23
10 | */
11 | public class MainActivity extends AppCompatActivity {
12 |
13 | @Override
14 | protected void onCreate(Bundle savedInstanceState) {
15 | super.onCreate(savedInstanceState);
16 | setContentView(R.layout.fragment_container);
17 | ActionBar actionBar = getSupportActionBar();
18 | if (actionBar != null) {
19 | actionBar.setDisplayHomeAsUpEnabled(false);
20 | }
21 |
22 | FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
23 | ft.add(R.id.container, new MainFragment()).commit();
24 | }
25 |
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/MainFragment.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.Nullable;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 |
9 | import com.chiclaim.rxjava.operator.CheckCacheFragment;
10 | import com.chiclaim.rxjava.operator.CombineLatestFragment;
11 | import com.chiclaim.rxjava.operator.HttpWithTokenFragment;
12 | import com.chiclaim.rxjava.operator.ObservableDependencyFragment;
13 | import com.chiclaim.rxjava.operator.SearchDebounceFragment;
14 | import com.chiclaim.rxjava.operator.TryWhenFragment;
15 | import com.chiclaim.rxjava.operator.create.CreateOperatorFragment;
16 | import com.chiclaim.rxjava.operator.transform.ConcatFlatMapFragment;
17 | import com.chiclaim.rxjava.operator.transform.FlatMapOperatorFragment;
18 | import com.chiclaim.rxjava.operator.transform.MapOperatorFragment;
19 |
20 | public class MainFragment extends BaseFragment implements View.OnClickListener {
21 |
22 | @Nullable
23 | @Override
24 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
25 | return inflater.inflate(R.layout.fragment_main, container, false);
26 | }
27 |
28 |
29 | @Override
30 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
31 | super.onViewCreated(view, savedInstanceState);
32 | view.findViewById(R.id.btn_create_just_from).setOnClickListener(this);
33 | view.findViewById(R.id.btn_map).setOnClickListener(this);
34 | view.findViewById(R.id.btn_flat_map).setOnClickListener(this);
35 | view.findViewById(R.id.btn_token).setOnClickListener(this);
36 | view.findViewById(R.id.btn_search_debounce).setOnClickListener(this);
37 | view.findViewById(R.id.btn_flat_concat_map).setOnClickListener(this);
38 | view.findViewById(R.id.btn_observable_dependence_on_other_observable).setOnClickListener(this);
39 | view.findViewById(R.id.btn_multiple_observables).setOnClickListener(this);
40 | view.findViewById(R.id.btn_retry_when_http_error).setOnClickListener(this);
41 | view.findViewById(R.id.btn_combine_latest).setOnClickListener(this);
42 | view.findViewById(R.id.btn_use_rxjava_in_right_way).setOnClickListener(this);
43 |
44 | }
45 |
46 |
47 | @Override
48 | public void onClick(View v) {
49 | switch (v.getId()) {
50 | case R.id.btn_create_just_from:
51 | addFragment(new CreateOperatorFragment());
52 | break;
53 | case R.id.btn_map:
54 | addFragment(new MapOperatorFragment());
55 | break;
56 | case R.id.btn_flat_map:
57 | addFragment(new FlatMapOperatorFragment());
58 | break;
59 | case R.id.btn_token:
60 | addFragment(new HttpWithTokenFragment());
61 | break;
62 | case R.id.btn_search_debounce:
63 | addFragment(new SearchDebounceFragment());
64 | break;
65 | case R.id.btn_flat_concat_map:
66 | addFragment(new ConcatFlatMapFragment());
67 | break;
68 | case R.id.btn_observable_dependence_on_other_observable:
69 | addFragment(new ObservableDependencyFragment());
70 | break;
71 | case R.id.btn_multiple_observables:
72 | addFragment(new CheckCacheFragment());
73 | break;
74 | case R.id.btn_retry_when_http_error:
75 | addFragment(new TryWhenFragment());
76 | break;
77 | case R.id.btn_combine_latest:
78 | addFragment(new CombineLatestFragment());
79 | break;
80 | case R.id.btn_use_rxjava_in_right_way:
81 | UseRxJavaRightWayActivity.launch(getActivity());
82 | break;
83 | }
84 | }
85 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/MyApplication.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava;
2 |
3 | import android.app.Application;
4 | import android.os.StrictMode;
5 |
6 | import com.squareup.leakcanary.LeakCanary;
7 |
8 | /**
9 | * Created by chiclaim on 2016/03/25
10 | */
11 | public class MyApplication extends Application {
12 | @Override
13 | public void onCreate() {
14 | StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
15 | .detectDiskReads()
16 | .detectDiskWrites()
17 | .detectNetwork() // or .detectAll() for all detectable problems
18 | .penaltyLog()
19 | .build());
20 |
21 | StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
22 | .detectLeakedSqlLiteObjects()
23 | .detectLeakedClosableObjects()
24 | .penaltyLog()
25 | .penaltyDeath()
26 | .build());
27 | super.onCreate();
28 |
29 | LeakCanary.install(this);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/UseRxJavaRightWayActivity.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.widget.TextView;
8 |
9 | import com.chiclaim.rxjava.api.ApiServiceFactory;
10 | import com.chiclaim.rxjava.api.UserApi;
11 |
12 | import retrofit.client.Response;
13 | import retrofit.mime.TypedByteArray;
14 | import rx.Subscription;
15 | import rx.android.schedulers.AndroidSchedulers;
16 | import rx.functions.Action1;
17 | import rx.schedulers.Schedulers;
18 | import rx.subscriptions.CompositeSubscription;
19 |
20 | /**
21 | * Created by chiclaim on 2016/03/31
22 | */
23 | public class UseRxJavaRightWayActivity extends AppCompatActivity {
24 |
25 | final UserApi userApi = ApiServiceFactory.createService(UserApi.class);
26 |
27 | CompositeSubscription compositeSubscription = new CompositeSubscription();
28 | Subscription subscriptionForUser;
29 | TextView tvContent;
30 |
31 | @Override
32 | protected void onCreate(Bundle savedInstanceState) {
33 | super.onCreate(savedInstanceState);
34 | setContentView(R.layout.activity_use_rxjava_right_way);
35 | tvContent = (TextView) findViewById(R.id.tv_content);
36 | subscriptionForUser = userApi.getUserInfo()
37 | .subscribeOn(Schedulers.io())
38 | .observeOn(AndroidSchedulers.mainThread())
39 | .subscribe(new Action1() {
40 | @Override
41 | public void call(Response response) {
42 | String content = new String(((TypedByteArray) response.getBody()).getBytes());
43 | tvContent.setText("receiver data : " + content);
44 | }
45 | }, new Action1() {
46 | @Override
47 | public void call(Throwable throwable) {
48 | tvContent.setText("receiver error : " + throwable.getMessage());
49 | }
50 | });
51 |
52 | compositeSubscription.add(subscriptionForUser);
53 |
54 | }
55 |
56 | public static void launch(Context context) {
57 | context.startActivity(new Intent(context, UseRxJavaRightWayActivity.class));
58 | }
59 |
60 | @Override
61 | protected void onStop() {
62 | super.onStop();
63 | }
64 |
65 | @Override
66 | protected void onResume() {
67 | super.onResume();
68 | }
69 |
70 | @Override
71 | protected void onDestroy() {
72 | super.onDestroy();
73 |
74 |
75 | //if (!subscriptionForUser.isUnsubscribed()) {
76 | // subscriptionForUser.unsubscribe();
77 | //}
78 |
79 |
80 | //avoid leak activity/fragment
81 | if (!compositeSubscription.isUnsubscribed()) {
82 | //调用compositeSubscription.unsubscribe()后 compositeSubscription 就不可用了.需要重新创建
83 | compositeSubscription.unsubscribe();
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/api/ApiServiceFactory.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava.api;
2 |
3 | import android.util.Log;
4 |
5 | import com.chiclaim.rxjava.exception.AccessDenyException;
6 | import com.chiclaim.rxjava.exception.ConversionException;
7 | import com.chiclaim.rxjava.exception.NetworkException;
8 | import com.chiclaim.rxjava.exception.UnKnowException;
9 |
10 | import retrofit.ErrorHandler;
11 | import retrofit.RequestInterceptor;
12 | import retrofit.RestAdapter;
13 | import retrofit.RetrofitError;
14 |
15 | /**
16 | * Created by chiclaim on 2016/01/26
17 | */
18 | public class ApiServiceFactory {
19 |
20 | //server source code please see:
21 | // https://github.com/chiclaim/android_mvvm_server
22 | private static final String BASE_URL = "http://10.1.67.34:8080/android_mvvm_server";
23 | // private static final String BASE_URL = "http://192.168.2.106:8080/AndroidMvvmServer";
24 | //http://10.1.67.34:8080/android_mvvm_server
25 |
26 | private static RequestInterceptor requestInterceptor = new RequestInterceptor() {
27 | @Override
28 | public void intercept(RequestFacade request) {
29 | request.addHeader("Authorization", "test");
30 | }
31 | };
32 |
33 | private static class NetWorkErrorHandler implements ErrorHandler {
34 | @Override
35 | public Throwable handleError(RetrofitError error) {
36 | retrofit.client.Response r = error.getResponse();
37 | if (r != null && r.getStatus() == 401) {
38 | Log.e("ErrorHandler", "---------> access deny code=401");
39 | return new AccessDenyException(error.getMessage());
40 | } else if (error.getKind() == RetrofitError.Kind.NETWORK) {
41 | Log.e("ErrorHandler", "---------> An IOException occurred while communicating to the server");
42 | return new NetworkException(error.getMessage());
43 | } else if (error.getKind() == RetrofitError.Kind.HTTP) {
44 | Log.e("ErrorHandler", "---------> A non-200 HTTP status code was received from the server");
45 | //return new Non200HttpException(cause.getMessage());
46 | } else if (error.getKind() == RetrofitError.Kind.CONVERSION) {
47 | Log.e("ErrorHandler", "---------> An exception was thrown while (de)serializing a body");
48 | return new ConversionException(error.getMessage());
49 | } else if (error.getKind() == RetrofitError.Kind.UNEXPECTED) {
50 | Log.e("ErrorHandler", "---------> An internal error occurred while attempting to execute a request. " +
51 | "It is best practice to re-throw this exception so your application crashes.");
52 | return new UnKnowException(error.getMessage());
53 | }
54 | return error.getCause();
55 | }
56 | }
57 |
58 | private static RestAdapter restAdapter = new RestAdapter
59 | .Builder()
60 | .setLogLevel(RestAdapter.LogLevel.FULL)
61 | .setEndpoint(BASE_URL)
62 | .setErrorHandler(new NetWorkErrorHandler())
63 | .setRequestInterceptor(requestInterceptor)
64 | .build();
65 |
66 |
67 | public static S createService(Class serviceClazz) {
68 | return restAdapter.create(serviceClazz);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/api/NetErrorType.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava.api;
2 |
3 |
4 | import com.chiclaim.rxjava.exception.ConversionException;
5 |
6 | /**
7 | * Created by chiclaim on 2016/02/26
8 | */
9 | public class NetErrorType {
10 |
11 | public static final int TYPE_ERROR_TIME_OUT = 1;
12 | public static final int TYPE_ERROR_UNKNOW_HOST = 2;
13 | public static final int TYPE_ERROR_CONNECT = 3;
14 | public static final int TYPE_ERROR_CONVERSION = 6;
15 | public static final int TYPE_ERROR_UNKNOW = 20;
16 |
17 | public static class ErrorType {
18 | public int type;
19 | public String msg;
20 |
21 | public ErrorType(int type, String msg) {
22 | this.type = type;
23 | this.msg = msg;
24 | }
25 | }
26 |
27 | public static ErrorType getErrorType(Throwable t) {
28 | if (t instanceof java.net.SocketTimeoutException) {
29 | return new ErrorType(TYPE_ERROR_TIME_OUT, "连接超时");
30 | } else if (t instanceof java.net.UnknownHostException) {
31 | return new ErrorType(TYPE_ERROR_UNKNOW_HOST, "网络不可用");
32 | } else if (t instanceof java.net.ConnectException) {
33 | return new ErrorType(TYPE_ERROR_CONNECT, "网络不可用");
34 | } else if (t instanceof ConversionException) {
35 | return new ErrorType(TYPE_ERROR_CONVERSION, "JSON解析失败");
36 | }
37 | return new ErrorType(TYPE_ERROR_UNKNOW, "未知错误");
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/api/SearchApi.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava.api;
2 |
3 | import java.util.List;
4 |
5 | import retrofit.http.GET;
6 | import retrofit.http.Query;
7 | import rx.Observable;
8 |
9 | /**
10 | * Created by chiclaim on 2016/02/26
11 | */
12 | public interface SearchApi {
13 |
14 | @GET("/search")
15 | Observable> search(@Query("key") String key);
16 |
17 | @GET("/hosts")
18 | Observable> hosts();
19 | }
20 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/api/UserApi.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava.api;
2 |
3 |
4 | import com.chiclaim.rxjava.model.AuthToken;
5 | import com.chiclaim.rxjava.model.User;
6 |
7 | import retrofit.client.Response;
8 | import retrofit.http.GET;
9 | import retrofit.http.Query;
10 | import rx.Observable;
11 |
12 | public interface UserApi {
13 |
14 | @GET("/token")
15 | AuthToken refreshToken();
16 |
17 | @GET("/userinfo")
18 | Observable getUserInfo();
19 |
20 |
21 | @GET("/userinfo?noToken=1")
22 | Observable getUserInfoNoToken();
23 |
24 | //wrong path
25 | @GET("/userinfo1")
26 | Observable getUserInfo1();
27 |
28 | @GET("/user/fetch")
29 | Observable fetchUserInfo(@Query("id") String key);
30 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/exception/AccessDenyException.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava.exception;
2 |
3 | /**
4 | * Created by chiclaim on 2016/02/25
5 | */
6 | public class AccessDenyException extends RuntimeException {
7 | public AccessDenyException(String detailMessage) {
8 | super(detailMessage);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/exception/ConversionException.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava.exception;
2 |
3 | /**
4 | * Created by chiclaim on 2016/02/26
5 | */
6 | public class ConversionException extends RuntimeException {
7 | public ConversionException(String detailMessage) {
8 | super(detailMessage);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/exception/NetworkException.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava.exception;
2 |
3 | /**
4 | * Created by chiclaim on 2016/02/25
5 | */
6 | public class NetworkException extends RuntimeException {
7 | public NetworkException(String detailMessage) {
8 | super(detailMessage);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiclaim/rxjava/exception/Non200HttpException.java:
--------------------------------------------------------------------------------
1 | package com.chiclaim.rxjava.exception;
2 |
3 | /**
4 | * A non-200 HTTP status code was received from the server