├── .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

5 | * Created by chiclaim on 2016/02/26 6 | */ 7 | public class Non200HttpException extends RuntimeException { 8 | public Non200HttpException(String detailMessage) { 9 | super(detailMessage); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/exception/UnKnowException.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.exception; 2 | 3 | /** 4 | * Created by chiclaim on 2016/02/26 5 | */ 6 | public class UnKnowException extends RuntimeException { 7 | public UnKnowException(String detailMessage) { 8 | super(detailMessage); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/model/AuthToken.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.model; 2 | 3 | /** 4 | * Created by chiclaim on 2016/02/24 5 | */ 6 | public class AuthToken { 7 | 8 | private String token; 9 | 10 | public String getToken() { 11 | return token; 12 | } 13 | 14 | public void setToken(String token) { 15 | this.token = token; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/model/User.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.model; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Description: 7 | *
8 | * Created by kumu on 2017/3/9. 9 | */ 10 | 11 | public class User { 12 | 13 | private int id; 14 | private String username; 15 | private String email; 16 | 17 | private List friends; 18 | 19 | public int getId() { 20 | return id; 21 | } 22 | 23 | public void setId(int id) { 24 | this.id = id; 25 | } 26 | 27 | public String getUsername() { 28 | return username; 29 | } 30 | 31 | public void setUsername(String username) { 32 | this.username = username; 33 | } 34 | 35 | public String getEmail() { 36 | return email; 37 | } 38 | 39 | public void setEmail(String email) { 40 | this.email = email; 41 | } 42 | 43 | public List getFriends() { 44 | return friends; 45 | } 46 | 47 | public void setFriends(List friends) { 48 | this.friends = friends; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/CheckCacheFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator; 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 | import android.widget.TextView; 9 | 10 | import com.chiclaim.rxjava.BaseFragment; 11 | import com.chiclaim.rxjava.R; 12 | 13 | import rx.Observable; 14 | import rx.Subscriber; 15 | import rx.android.schedulers.AndroidSchedulers; 16 | import rx.functions.Action1; 17 | import rx.functions.Func1; 18 | import rx.schedulers.Schedulers; 19 | 20 | /** 21 | * Retrieve data from Multiple Observables
22 | * Created by chiclaim on 2016/03/29 23 | */ 24 | public class CheckCacheFragment extends BaseFragment { 25 | 26 | 27 | TextView tvLogs; 28 | 29 | @Nullable 30 | @Override 31 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 32 | return inflater.inflate(R.layout.fragment_check_data, container, false); 33 | } 34 | 35 | @Override 36 | public void onViewCreated(View view, Bundle savedInstanceState) { 37 | super.onViewCreated(view, savedInstanceState); 38 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 39 | view.findViewById(R.id.btn_operator).setOnClickListener(this); 40 | } 41 | 42 | String data[] = {null, null, "network"}; 43 | //String data[] = {null, "disk","network"}; 44 | //String data[] = {"memory", null,"network"}; 45 | //String data[] = {"memory", "disk",null}; 46 | //String data[] = {"memory", "disk","network"}; 47 | 48 | private Observable memorySource = Observable.create(new Observable.OnSubscribe() { 49 | @Override 50 | public void call(Subscriber subscriber) { 51 | String d = data[0]; 52 | printLog(tvLogs, "", "----start check memory data. value is null? " + (d == null)); 53 | if (d != null) { 54 | subscriber.onNext(d); 55 | } 56 | subscriber.onCompleted(); 57 | } 58 | }); 59 | 60 | 61 | private Observable diskSource = Observable.create(new Observable.OnSubscribe() { 62 | @Override 63 | public void call(Subscriber subscriber) { 64 | String d = data[1]; 65 | printLog(tvLogs, "", "----start check disk data. value is null? " + (d == null)); 66 | if (d != null) { 67 | subscriber.onNext(d); 68 | } 69 | subscriber.onCompleted(); 70 | } 71 | }).subscribeOn(Schedulers.io()); 72 | 73 | 74 | private Observable networkSource = Observable.create(new Observable.OnSubscribe() { 75 | @Override 76 | public void call(Subscriber subscriber) { 77 | String d = data[2]; 78 | printLog(tvLogs, "", "----start check network data. value is null? " + (d == null)); 79 | if (d != null) { 80 | subscriber.onNext(d); 81 | } 82 | subscriber.onCompleted(); 83 | } 84 | }).subscribeOn(Schedulers.io()); 85 | 86 | 87 | 88 | @Override 89 | public void onClick(View v) { 90 | super.onClick(v); 91 | switch (v.getId()) { 92 | case R.id.btn_operator: 93 | tvLogs.setText(""); 94 | Observable.concat(memorySource, diskSource, networkSource) 95 | //first()-> if no data from observables will cause exception : 96 | //java.util.NoSuchElementException: Sequence contains no elements 97 | //takeFirst -> no exception 98 | .takeFirst(new Func1() { 99 | @Override 100 | public Boolean call(String s) { 101 | return s != null; 102 | } 103 | }) 104 | .observeOn(AndroidSchedulers.mainThread()) 105 | .subscribe(new Action1() { 106 | @Override 107 | public void call(String s) { 108 | printLog(tvLogs, "Getting data from ", s); 109 | } 110 | }, new Action1() { 111 | @Override 112 | public void call(Throwable throwable) { 113 | throwable.printStackTrace(); 114 | printLog(tvLogs, "Error: ", throwable.getMessage()); 115 | } 116 | }); 117 | break; 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/CombineLatestFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator; 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 | import android.widget.TextView; 9 | 10 | import com.chiclaim.rxjava.BaseFragment; 11 | import com.chiclaim.rxjava.R; 12 | import com.chiclaim.rxjava.api.ApiServiceFactory; 13 | import com.chiclaim.rxjava.api.UserApi; 14 | import com.chiclaim.rxjava.model.User; 15 | 16 | import java.util.List; 17 | 18 | import rx.Observable; 19 | import rx.android.schedulers.AndroidSchedulers; 20 | import rx.functions.Action1; 21 | import rx.functions.Func1; 22 | import rx.functions.Func2; 23 | import rx.schedulers.Schedulers; 24 | 25 | /** 26 | * Description:CombineLatest操作符高级用法 27 | *
28 | * Created by kumu on 2017/3/9. 29 | */ 30 | 31 | public class CombineLatestFragment extends BaseFragment { 32 | 33 | UserApi userApi; 34 | TextView tvLogs; 35 | 36 | @Nullable 37 | @Override 38 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 39 | return inflater.inflate(R.layout.fragment_combine_latest, container, false); 40 | } 41 | 42 | @Override 43 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 44 | super.onViewCreated(view, savedInstanceState); 45 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 46 | 47 | userApi = ApiServiceFactory.createService(UserApi.class); 48 | userApi.fetchUserInfo(null) 49 | .flatMap(new Func1>() { 50 | @Override 51 | public Observable call(User user) { 52 | printLog(tvLogs, "----fetch a user---- \n", getUserString(user)); 53 | return fetchFriendsInfo(user); 54 | } 55 | }) 56 | .subscribeOn(Schedulers.io()) 57 | .observeOn(AndroidSchedulers.mainThread()) 58 | .subscribe(new Action1() { 59 | @Override 60 | public void call(User user) { 61 | printLog(tvLogs, "----process his friends by id---- \n", getUserString(user)); 62 | } 63 | }, new Action1() { 64 | @Override 65 | public void call(Throwable throwable) { 66 | throwable.printStackTrace(); 67 | } 68 | }); 69 | } 70 | 71 | private Observable fetchFriendsInfo(User user) { 72 | 73 | Observable observableUser = Observable.just(user); 74 | 75 | Observable> observableUsers = Observable 76 | .from(user.getFriends()) 77 | .flatMap(new Func1>() { 78 | @Override 79 | public Observable call(User user) { 80 | return userApi.fetchUserInfo(user.getId() + ""); 81 | } 82 | }) 83 | .toList(); 84 | 85 | return Observable.combineLatest(observableUser, observableUsers, new Func2, User>() { 86 | @Override 87 | public User call(User user, List users) { 88 | user.setFriends(users); 89 | return user; 90 | } 91 | }); 92 | } 93 | 94 | private String getUserString(User user) { 95 | StringBuilder sb = new StringBuilder(); 96 | sb.append("name:").append(user.getUsername()).append(", email:").append(user.getEmail()) 97 | .append(" \n\tHis friends:"); 98 | for (User friend : user.getFriends()) { 99 | sb.append("\n\t\t").append("id:").append(friend.getId()) 100 | .append(", name:").append(friend.getUsername()).append(", email:").append(friend.getEmail()); 101 | } 102 | return sb.toString(); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/HttpWithTokenFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator; 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 | import android.widget.TextView; 9 | 10 | import com.chiclaim.rxjava.BaseFragment; 11 | import com.chiclaim.rxjava.R; 12 | import com.chiclaim.rxjava.api.ApiServiceFactory; 13 | import com.chiclaim.rxjava.api.NetErrorType; 14 | import com.chiclaim.rxjava.api.UserApi; 15 | import com.chiclaim.rxjava.exception.AccessDenyException; 16 | import com.chiclaim.rxjava.model.AuthToken; 17 | 18 | import retrofit.client.Response; 19 | import retrofit.mime.TypedByteArray; 20 | import rx.Observable; 21 | import rx.Observer; 22 | import rx.Subscriber; 23 | import rx.android.schedulers.AndroidSchedulers; 24 | import rx.functions.Func1; 25 | import rx.schedulers.Schedulers; 26 | 27 | /** 28 | * Created by chiclaim on 2016/03/24 29 | */ 30 | public class HttpWithTokenFragment extends BaseFragment { 31 | 32 | private final UserApi userApi = ApiServiceFactory.createService(UserApi.class); 33 | private TextView tvLogs; 34 | private boolean loading; 35 | 36 | 37 | @Nullable 38 | @Override 39 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 40 | return inflater.inflate(R.layout.fragment_http_token, container, false); 41 | } 42 | 43 | @Override 44 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 45 | super.onViewCreated(view, savedInstanceState); 46 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 47 | view.findViewById(R.id.btn_request).setOnClickListener(this); 48 | requestUserInfo(); 49 | } 50 | 51 | 52 | public Observable createTokenObvervable() { 53 | return Observable.create(new Observable.OnSubscribe() { 54 | @Override 55 | public void call(Subscriber observer) { 56 | try { 57 | if (!observer.isUnsubscribed()) { 58 | appendText(tvLogs, "God!!! Token is out of date. \nstart refresh token......"); 59 | observer.onNext(userApi.refreshToken()); 60 | observer.onCompleted(); 61 | } 62 | } catch (Exception e) { 63 | observer.onError(e); 64 | } 65 | } 66 | }).subscribeOn(Schedulers.io()); 67 | } 68 | 69 | private Func1> refreshTokenAndRetry(final Observable toBeResumed) { 70 | return new Func1>() { 71 | @Override 72 | public Observable call(Throwable throwable) { 73 | throwable.printStackTrace(); 74 | // Here check if the error thrown really is a 401 75 | if (isHttp401Error(throwable)) { 76 | return createTokenObvervable().flatMap(new Func1>() { 77 | @Override 78 | public Observable call(AuthToken token) { 79 | appendText(tvLogs, "refresh token success,token's validity is 10s\nResume last request"); 80 | return toBeResumed; 81 | } 82 | }); 83 | } 84 | // re-throw this error because it's not recoverable from here 85 | return Observable.error(throwable); 86 | } 87 | 88 | public boolean isHttp401Error(Throwable throwable) { 89 | return throwable instanceof AccessDenyException; 90 | } 91 | 92 | }; 93 | } 94 | 95 | private void requestUserInfo() { 96 | appendText(tvLogs, "start to request user info"); 97 | loading = true; 98 | Observable observable = userApi.getUserInfo(); 99 | observable.onErrorResumeNext(refreshTokenAndRetry(observable))//also use retryWhen to implement it 100 | .subscribeOn(Schedulers.io()) 101 | .observeOn(AndroidSchedulers.mainThread()) 102 | .subscribe(new Observer() { 103 | @Override 104 | public void onCompleted() { 105 | loading = false; 106 | appendText(tvLogs, "task completed-----"); 107 | //hideLoadingDialog(); 108 | } 109 | 110 | @Override 111 | public void onError(Throwable t) { 112 | //hideLoadingDialog(); 113 | t.printStackTrace(); 114 | loading = false; 115 | 116 | appendText(tvLogs, t.getClass().getName() + "\n" + t.getMessage()); 117 | NetErrorType.ErrorType error = NetErrorType.getErrorType(t); 118 | appendText(tvLogs, error.msg); 119 | } 120 | 121 | public void onNext(Response response) { 122 | String content = new String(((TypedByteArray) response.getBody()).getBytes()); 123 | appendText(tvLogs, "receiver data: " + content); 124 | } 125 | }); 126 | } 127 | 128 | @Override 129 | public void onClick(View v) { 130 | super.onClick(v); 131 | switch (v.getId()) { 132 | case R.id.btn_request: 133 | if (!loading) { 134 | tvLogs.append("\n\n--------------------------------"); 135 | requestUserInfo(); 136 | } 137 | break; 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/ObservableDependencyFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator; 2 | 3 | import android.os.Bundle; 4 | import android.os.Handler; 5 | import android.os.Looper; 6 | import android.support.annotation.Nullable; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.TextView; 11 | 12 | import com.chiclaim.rxjava.BaseFragment; 13 | import com.chiclaim.rxjava.R; 14 | import com.chiclaim.rxjava.api.ApiServiceFactory; 15 | import com.chiclaim.rxjava.api.SearchApi; 16 | 17 | import java.net.InetAddress; 18 | import java.net.MalformedURLException; 19 | import java.net.URL; 20 | import java.net.UnknownHostException; 21 | import java.util.List; 22 | 23 | import rx.Observable; 24 | import rx.Subscriber; 25 | import rx.android.schedulers.AndroidSchedulers; 26 | import rx.functions.Action1; 27 | import rx.functions.Func1; 28 | import rx.schedulers.Schedulers; 29 | 30 | /** 31 | * Created by chiclaim on 2016/03/29 32 | */ 33 | public class ObservableDependencyFragment extends BaseFragment { 34 | 35 | private final SearchApi searchApi = ApiServiceFactory.createService(SearchApi.class); 36 | 37 | private TextView tvLogs; 38 | 39 | @Nullable 40 | @Override 41 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 42 | return inflater.inflate(R.layout.fragment_observable_dependency, container, false); 43 | } 44 | 45 | 46 | @Override 47 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 48 | super.onViewCreated(view, savedInstanceState); 49 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 50 | view.findViewById(R.id.btn_operator).setOnClickListener(this); 51 | } 52 | 53 | 54 | private String getIPByUrl(String str) throws MalformedURLException, UnknownHostException { 55 | URL urls = new URL(str); 56 | String host = urls.getHost(); 57 | String address = InetAddress.getByName(host).toString(); 58 | int b = address.indexOf("/"); 59 | return address.substring(b + 1); 60 | 61 | } 62 | 63 | 64 | private Observable createIpObservable(final String url) { 65 | return Observable.create(new Observable.OnSubscribe() { 66 | @Override 67 | public void call(Subscriber subscriber) { 68 | try { 69 | String ip = getIPByUrl(url); 70 | subscriber.onNext(ip); 71 | printLog(tvLogs, "Emit Data -> ", ip); 72 | } catch (MalformedURLException e) { 73 | e.printStackTrace(); 74 | //subscriber.onError(e); 75 | subscriber.onNext(null); 76 | } catch (UnknownHostException e) { 77 | e.printStackTrace(); 78 | //subscriber.onError(e); 79 | subscriber.onNext(null); 80 | } 81 | subscriber.onCompleted(); 82 | } 83 | }).subscribeOn(Schedulers.io()); 84 | } 85 | 86 | 87 | private void setTextHosts(final List strings) { 88 | new Handler(Looper.getMainLooper()).post(new Runnable() { 89 | @Override 90 | public void run() { 91 | tvLogs.setText("-------Got hosts from server :\n"); 92 | for (String host : strings) { 93 | tvLogs.append(host); 94 | tvLogs.append("\n"); 95 | } 96 | tvLogs.append("\n-------Start to get ip by host\n"); 97 | } 98 | }); 99 | } 100 | 101 | 102 | private void processClick() { 103 | //When your want to get ip , you must retrieve hosts first. 104 | searchApi.hosts() 105 | .flatMap(new Func1, Observable>() { 106 | @Override 107 | public Observable call(List strings) { 108 | setTextHosts(strings); 109 | return Observable.from(strings); 110 | } 111 | }) 112 | .flatMap(new Func1>() { 113 | @Override 114 | public Observable call(String s) { 115 | return createIpObservable(s); 116 | } 117 | }) 118 | .observeOn(AndroidSchedulers.mainThread()) 119 | .subscribe(new Action1() { 120 | @Override 121 | public void call(String s) { 122 | printLog(tvLogs, "Consume Data <- ", s); 123 | } 124 | }, new Action1() { 125 | @Override 126 | public void call(Throwable throwable) { 127 | printErrorLog(tvLogs, "throwable call()", throwable.getMessage()); 128 | } 129 | }); 130 | } 131 | 132 | @Override 133 | public void onClick(View v) { 134 | super.onClick(v); 135 | switch (v.getId()) { 136 | case R.id.btn_operator: 137 | processClick(); 138 | break; 139 | } 140 | } 141 | } -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/RetryWithDelay.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator; 2 | 3 | import android.util.Log; 4 | 5 | import java.util.concurrent.TimeUnit; 6 | 7 | import rx.Observable; 8 | import rx.functions.Func1; 9 | 10 | public class RetryWithDelay implements 11 | Func1, Observable> { 12 | 13 | private final int maxRetries; 14 | private final int retryDelayMillis; 15 | private int retryCount; 16 | 17 | public RetryWithDelay(final int maxRetries, final int retryDelayMillis) { 18 | this.maxRetries = maxRetries; 19 | this.retryDelayMillis = retryDelayMillis; 20 | this.retryCount = 0; 21 | } 22 | 23 | @Override 24 | public Observable call(Observable attempts) { 25 | return attempts 26 | .flatMap(new Func1>() { 27 | @Override 28 | public Observable call(Throwable throwable) { 29 | if (++retryCount <= maxRetries) { 30 | // When this Observable calls onNext, the original 31 | // Observable will be retried (i.e. re-subscribed). 32 | Log.d("Retry", "get error, retry again " + retryCount); 33 | return Observable.timer(retryDelayMillis, 34 | TimeUnit.MILLISECONDS); 35 | } 36 | 37 | // Max retries hit. Just pass the error along. 38 | return Observable.error(throwable); 39 | } 40 | }); 41 | } 42 | } -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/SearchDebounceFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator; 2 | 3 | import android.os.Bundle; 4 | import android.os.Looper; 5 | import android.support.annotation.Nullable; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | import android.widget.EditText; 10 | import android.widget.TextView; 11 | 12 | import com.chiclaim.rxjava.BaseFragment; 13 | import com.chiclaim.rxjava.R; 14 | import com.chiclaim.rxjava.api.ApiServiceFactory; 15 | import com.chiclaim.rxjava.api.SearchApi; 16 | import com.jakewharton.rxbinding.widget.RxTextView; 17 | 18 | import java.util.List; 19 | import java.util.concurrent.TimeUnit; 20 | 21 | import rx.Observable; 22 | import rx.Subscription; 23 | import rx.android.schedulers.AndroidSchedulers; 24 | import rx.functions.Action1; 25 | import rx.functions.Func1; 26 | import rx.schedulers.Schedulers; 27 | 28 | /** 29 | * Created by chiclaim on 2016/03/24 30 | */ 31 | public class SearchDebounceFragment extends BaseFragment { 32 | 33 | private final SearchApi searchApi = ApiServiceFactory.createService(SearchApi.class); 34 | 35 | 36 | private Subscription subscription; 37 | 38 | 39 | private TextView tvContent; 40 | private EditText etKey; 41 | private TextView tvKey; 42 | 43 | 44 | @Nullable 45 | @Override 46 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 47 | return inflater.inflate(R.layout.fragment_search, container, false); 48 | } 49 | 50 | @Override 51 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 52 | super.onViewCreated(view, savedInstanceState); 53 | tvContent = (TextView) view.findViewById(R.id.tv_content); 54 | etKey = (EditText) view.findViewById(R.id.et_key); 55 | tvKey = (TextView) view.findViewById(R.id.tv_key); 56 | 57 | 58 | //===========================@TODO 59 | //1,避免EditText每改变一次就请求一次. 60 | //2,避免频繁的请求,多个导致结果顺序错乱,最终的结果也就有问题. 61 | 62 | // 但是对于第二个问题,也不能彻底的解决,但是从一定程度上缓解了错乱的问题. 比如停止输入400毫秒后, 63 | // 那么肯定会开始请求Search接口, 但是用户又会输入新的关键字, 64 | // 这个时候上个请求还没有返回, 新的请求又去请求Search接口. 65 | // 这个时候有可能最后的一个请求返回, 第一个请求最后返回,导致搜索结果不是想要的. 66 | //===========================@TODO 67 | 68 | 69 | subscription = RxTextView.textChanges(etKey) 70 | // 对etKey[EditText]的监听操作 需要在主线程操作 71 | .subscribeOn(AndroidSchedulers.mainThread()) 72 | .debounce(400, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) 73 | //对应用输入的关键字进行过滤 74 | .filter(new Func1() { 75 | @Override 76 | public Boolean call(CharSequence charSequence) { 77 | tvContent.setText(""); 78 | appendText(tvContent, "filter is main thread : " + (Looper.getMainLooper() == Looper.myLooper())); 79 | return charSequence.toString().trim().length() > 0; 80 | } 81 | }) 82 | .switchMap(new Func1>>() { 83 | @Override 84 | public Observable> call(CharSequence charSequence) { 85 | appendText(tvContent, "switchMap is main thread : " + (Looper.getMainLooper() == Looper.myLooper())); 86 | return searchApi.search(charSequence.toString()).flatMap(new Func1, Observable>>() { 87 | @Override 88 | public Observable> call(List strings) { 89 | //测试searchApi.search是不是默认在子线程中执行. 90 | appendText(tvContent, "switchMap flatMap transform : " + (Looper.getMainLooper() == Looper.myLooper())); 91 | return Observable.just(strings); 92 | } 93 | }); 94 | } 95 | }) 96 | //@TODO 无法使得switchMap在子线程中执行, 待查明??? 97 | .subscribeOn(Schedulers.io()) 98 | // .flatMap(new Func1, Observable>() { 99 | // @Override 100 | // public Observable call(List strings) { 101 | // appendText(tvContent, "flatMap transform : " + (Looper.getMainLooper() == Looper.myLooper())); 102 | // return Observable.from(strings); 103 | // } 104 | // }) 105 | // .filter(new Func1() { 106 | // @Override 107 | // public Boolean call(String s) { 108 | // //appendText(tvContent, s + " length > 3: " + (s.length() > 3) + " thread: " + (Looper.getMainLooper() == Looper.myLooper())); 109 | // return s.length() > 3; 110 | // } 111 | // }) 112 | //.toList() 113 | .observeOn(AndroidSchedulers.mainThread()) 114 | .subscribe(new Action1>() { 115 | @Override 116 | public void call(List strings) { 117 | appendText(tvContent, "subscribe call is main thread : " + (Looper.getMainLooper() == Looper.myLooper())); 118 | tvContent.append("\n\nsearch result:\n\n "); 119 | tvContent.append(strings.toString()); 120 | } 121 | }, new Action1() { 122 | @Override 123 | public void call(Throwable throwable) { 124 | throwable.printStackTrace(); 125 | tvContent.append("Error:" + throwable.getMessage()); 126 | } 127 | }); 128 | //flatMap和switchMap的区别 129 | } 130 | 131 | @Override 132 | public void onDestroy() { 133 | super.onDestroy(); 134 | if (!subscription.isUnsubscribed()) { 135 | subscription.unsubscribe(); 136 | } 137 | } 138 | 139 | } 140 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/TryWhenFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator; 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 | import android.widget.TextView; 9 | 10 | import com.chiclaim.rxjava.BaseFragment; 11 | import com.chiclaim.rxjava.R; 12 | import com.chiclaim.rxjava.api.ApiServiceFactory; 13 | import com.chiclaim.rxjava.api.UserApi; 14 | 15 | import java.util.concurrent.TimeUnit; 16 | 17 | import retrofit.client.Response; 18 | import retrofit.mime.TypedByteArray; 19 | import rx.Observable; 20 | import rx.android.schedulers.AndroidSchedulers; 21 | import rx.functions.Action1; 22 | import rx.functions.Func1; 23 | import rx.schedulers.Schedulers; 24 | 25 | /** 26 | * Created by chiclaim on 2016/03/31 27 | */ 28 | public class TryWhenFragment extends BaseFragment { 29 | 30 | private final UserApi userApi = ApiServiceFactory.createService(UserApi.class); 31 | 32 | private TextView tvLogs; 33 | 34 | @Nullable 35 | @Override 36 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 37 | return inflater.inflate(R.layout.fragment_retry_when, container, false); 38 | } 39 | 40 | 41 | @Override 42 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 43 | super.onViewCreated(view, savedInstanceState); 44 | view.findViewById(R.id.btn_operator).setOnClickListener(this); 45 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 46 | } 47 | 48 | @Override 49 | public void onClick(View v) { 50 | super.onClick(v); 51 | switch (v.getId()) { 52 | case R.id.btn_operator: 53 | tvLogs.setText(""); 54 | userApi.getUserInfoNoToken() 55 | .retryWhen(new RetryWithDelay(3, 3000)) 56 | .observeOn(AndroidSchedulers.mainThread()) 57 | .subscribeOn(Schedulers.io()) 58 | .subscribe(new Action1() { 59 | @Override 60 | public void call(Response response) { 61 | String content = new String(((TypedByteArray) response.getBody()).getBytes()); 62 | printLog(tvLogs, "", content); 63 | } 64 | }, new Action1() { 65 | @Override 66 | public void call(Throwable throwable) { 67 | throwable.printStackTrace(); 68 | } 69 | }); 70 | } 71 | } 72 | 73 | public class RetryWithDelay implements 74 | Func1, Observable> { 75 | 76 | private final int maxRetries; 77 | private final int retryDelayMillis; 78 | private int retryCount; 79 | 80 | public RetryWithDelay(int maxRetries, int retryDelayMillis) { 81 | this.maxRetries = maxRetries; 82 | this.retryDelayMillis = retryDelayMillis; 83 | this.retryCount = 0; 84 | } 85 | 86 | @Override 87 | public Observable call(Observable attempts) { 88 | return attempts 89 | .flatMap(new Func1>() { 90 | @Override 91 | public Observable call(Throwable throwable) { 92 | if (++retryCount <= maxRetries) { 93 | // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed). 94 | printLog(tvLogs, "", "get error, it will try after " + retryDelayMillis 95 | + " millisecond, retry count " + retryCount); 96 | return Observable.timer(retryDelayMillis, 97 | TimeUnit.MILLISECONDS); 98 | } 99 | // Max retries hit. Just pass the error along. 100 | return Observable.error(throwable); 101 | } 102 | }); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/create/CreateOperatorFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator.create; 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 | import android.widget.TextView; 9 | 10 | import com.chiclaim.rxjava.BaseFragment; 11 | import com.chiclaim.rxjava.R; 12 | 13 | import rx.Observable; 14 | import rx.Subscriber; 15 | import rx.android.schedulers.AndroidSchedulers; 16 | import rx.functions.Action1; 17 | import rx.schedulers.Schedulers; 18 | 19 | /** 20 | * Created by chiclaim on 2016/03/23 21 | */ 22 | public class CreateOperatorFragment extends BaseFragment { 23 | 24 | 25 | private TextView tvLogs; 26 | 27 | @Nullable 28 | @Override 29 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 30 | return inflater.inflate(R.layout.fragment_create_operator, container, false); 31 | } 32 | 33 | @Override 34 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 35 | super.onViewCreated(view, savedInstanceState); 36 | view.findViewById(R.id.btn_create).setOnClickListener(this); 37 | view.findViewById(R.id.btn_just).setOnClickListener(this); 38 | view.findViewById(R.id.btn_from).setOnClickListener(this); 39 | 40 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 41 | tvLogs.setText("Click Button to test 'map operator'"); 42 | 43 | } 44 | 45 | 46 | private void observableCreate() { 47 | Observable 48 | .create(new Observable.OnSubscribe() { 49 | @Override 50 | public void call(Subscriber subscriber) { 51 | for (int i = 0; i < 5; i++) { 52 | printLog(tvLogs, "Emit Data:", i + ""); 53 | subscriber.onNext("" + i); 54 | } 55 | } 56 | }) 57 | .observeOn(AndroidSchedulers.mainThread()) 58 | .subscribeOn(Schedulers.io()).subscribe(new Action1() { 59 | @Override 60 | public void call(String s) { 61 | //showToast(s); 62 | printLog(tvLogs, "Consume Data:", s); 63 | } 64 | }); 65 | } 66 | 67 | 68 | private void observableJust() { 69 | Observable.just("hello", "world").subscribe(new Action1() { 70 | @Override 71 | public void call(String s) { 72 | printLog(tvLogs, "Consume Data : ", s); 73 | } 74 | }); 75 | } 76 | 77 | 78 | private void observableFrom() { 79 | Observable sentenceObservable = Observable.from(new String[]{"This", "is", "RxJava"}); 80 | sentenceObservable.subscribe(new Action1() { 81 | @Override 82 | public void call(String s) { 83 | printLog(tvLogs, "Consume Data : ", s); 84 | } 85 | }); 86 | } 87 | 88 | @Override 89 | public void onClick(View v) { 90 | super.onClick(v); 91 | switch (v.getId()) { 92 | case R.id.btn_create: 93 | tvLogs.setText(""); 94 | observableCreate(); 95 | break; 96 | case R.id.btn_just: 97 | tvLogs.setText(""); 98 | observableJust(); 99 | break; 100 | case R.id.btn_from: 101 | tvLogs.setText(""); 102 | observableFrom(); 103 | break; 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/transform/ConcatFlatMapFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator.transform; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.text.TextUtils; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | import android.widget.TextView; 10 | 11 | import com.chiclaim.rxjava.BaseFragment; 12 | import com.chiclaim.rxjava.R; 13 | 14 | import java.net.InetAddress; 15 | import java.net.MalformedURLException; 16 | import java.net.URL; 17 | import java.net.UnknownHostException; 18 | import java.util.Arrays; 19 | import java.util.List; 20 | 21 | import rx.Observable; 22 | import rx.Subscriber; 23 | import rx.android.schedulers.AndroidSchedulers; 24 | import rx.functions.Action1; 25 | import rx.functions.Func1; 26 | import rx.schedulers.Schedulers; 27 | 28 | /** 29 | * flatMap compare with concatMap
30 | * Created by chiclaim on 2016/03/28 31 | */ 32 | public class ConcatFlatMapFragment extends BaseFragment { 33 | 34 | TextView tvLogs; 35 | 36 | @Nullable 37 | @Override 38 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 39 | return inflater.inflate(R.layout.fragment_concat_flat_map_layout, container, false); 40 | } 41 | 42 | @Override 43 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 44 | super.onViewCreated(view, savedInstanceState); 45 | 46 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 47 | 48 | view.findViewById(R.id.btn_concat_one_thread).setOnClickListener(this); 49 | view.findViewById(R.id.btn_concat_multiple_threads).setOnClickListener(this); 50 | view.findViewById(R.id.btn_flat_one_thread).setOnClickListener(this); 51 | view.findViewById(R.id.btn_flat_multiple_threads).setOnClickListener(this); 52 | } 53 | 54 | 55 | private String getIPByUrl(String str) throws MalformedURLException, UnknownHostException { 56 | URL urls = new URL(str); 57 | String host = urls.getHost(); 58 | String address = InetAddress.getByName(host).toString(); 59 | int b = address.indexOf("/"); 60 | return address.substring(b + 1); 61 | 62 | } 63 | 64 | 65 | private synchronized Observable createIpObservableMultiThread(final String url) { 66 | return Observable 67 | .create(new Observable.OnSubscribe() { 68 | @Override 69 | public void call(Subscriber subscriber) { 70 | try { 71 | String ip = getIPByUrl(url); 72 | printLog(tvLogs, "Emit Data -> ", url + "->" + ip); 73 | subscriber.onNext(ip); 74 | } catch (MalformedURLException e) { 75 | e.printStackTrace(); 76 | //subscriber.onError(e); 77 | subscriber.onNext(null); 78 | } catch (UnknownHostException e) { 79 | e.printStackTrace(); 80 | //subscriber.onError(e); 81 | subscriber.onNext(null); 82 | } 83 | subscriber.onCompleted(); 84 | } 85 | }) 86 | .subscribeOn(Schedulers.io()); 87 | //.subscribeOn(Schedulers.io()) 注意该方法在这里调用和放在使用该Observable的地方调 产生不同的影响 88 | //把注释去掉会使用不同的线程去执行,放在放在使用该Observable的地方调会共用一个线程去执行 89 | } 90 | 91 | private synchronized Observable createIpObservableOneThread(final String url) { 92 | return Observable.create(new Observable.OnSubscribe() { 93 | @Override 94 | public void call(Subscriber subscriber) { 95 | try { 96 | String ip = getIPByUrl(url); 97 | printLog(tvLogs, "Emit Data -> ", url + "->" + ip); 98 | subscriber.onNext(ip); 99 | } catch (MalformedURLException e) { 100 | e.printStackTrace(); 101 | //subscriber.onError(e); 102 | subscriber.onNext(null); 103 | } catch (UnknownHostException e) { 104 | e.printStackTrace(); 105 | //subscriber.onError(e); 106 | subscriber.onNext(null); 107 | } 108 | subscriber.onCompleted(); 109 | } 110 | }); 111 | } 112 | 113 | 114 | List urls = Arrays.asList( 115 | "http://www.baidu.com/", 116 | "http://www.google.com/", 117 | "https://www.bing.com/"); 118 | 119 | public Observable createUrlObservable() { 120 | return Observable.from(urls); 121 | } 122 | 123 | private Observable processUrlIpByConcatMapOneThread() { 124 | return createUrlObservable() 125 | .concatMap(new Func1>() { 126 | @Override 127 | public Observable call(String s) { 128 | return createIpObservableOneThread(s); 129 | } 130 | }) 131 | .subscribeOn(Schedulers.io()) 132 | .observeOn(AndroidSchedulers.mainThread()); 133 | } 134 | 135 | 136 | private Observable processUrlIpByConcatMapMultipleThread() { 137 | return createUrlObservable() 138 | .concatMap(new Func1>() { 139 | @Override 140 | public Observable call(String s) { 141 | return createIpObservableMultiThread(s); 142 | } 143 | }).filter(new Func1() { 144 | //filter data [if result is null or empty ,it will be ignored] 145 | @Override 146 | public Boolean call(String s) { 147 | return !TextUtils.isEmpty(s); 148 | } 149 | }) 150 | //.subscribeOn(Schedulers.io()) 151 | .observeOn(AndroidSchedulers.mainThread()); 152 | } 153 | 154 | private Observable processUrlIpByFlatMapMultipleThread() { 155 | return createUrlObservable() 156 | .flatMap(new Func1>() { 157 | @Override 158 | public Observable call(String s) { 159 | //Log.d("call", getMainText("call")); 160 | return createIpObservableMultiThread(s); 161 | } 162 | }).filter(new Func1() { 163 | //filter data [if result is null or empty ,it will be ignored] 164 | @Override 165 | public Boolean call(String s) { 166 | return !TextUtils.isEmpty(s); 167 | } 168 | }) 169 | //.subscribeOn(Schedulers.io()) 170 | .observeOn(AndroidSchedulers.mainThread()); 171 | } 172 | 173 | 174 | private Observable processUrlIpByFlatMapOneThread() { 175 | return createUrlObservable() 176 | .flatMap(new Func1>() { 177 | @Override 178 | public Observable call(String s) { 179 | return createIpObservableOneThread(s); 180 | } 181 | }) 182 | .subscribeOn(Schedulers.io()) 183 | .observeOn(AndroidSchedulers.mainThread()); 184 | } 185 | 186 | 187 | private void subscribe(Observable observable) { 188 | observable.subscribe(new Action1() { 189 | @Override 190 | public void call(String s) { 191 | printLog(tvLogs, "Consume Data <- ", s); 192 | } 193 | }, new Action1() { 194 | @Override 195 | public void call(Throwable throwable) { 196 | throwable.printStackTrace(); 197 | printErrorLog(tvLogs, "throwable call()", throwable.getMessage()); 198 | } 199 | }); 200 | } 201 | 202 | 203 | private void resetLogs() { 204 | tvLogs.setText("Original Stream Order:"); 205 | for (String url : urls) { 206 | tvLogs.append("\n"); 207 | tvLogs.append(url); 208 | } 209 | } 210 | 211 | @Override 212 | public void onClick(View v) { 213 | super.onClick(v); 214 | // concat(); 215 | switch (v.getId()) { 216 | case R.id.btn_concat_one_thread: 217 | resetLogs(); 218 | subscribe(processUrlIpByConcatMapOneThread()); 219 | break; 220 | case R.id.btn_concat_multiple_threads: 221 | resetLogs(); 222 | subscribe(processUrlIpByConcatMapMultipleThread()); 223 | break; 224 | case R.id.btn_flat_one_thread: 225 | resetLogs(); 226 | subscribe(processUrlIpByFlatMapOneThread()); 227 | break; 228 | case R.id.btn_flat_multiple_threads: 229 | resetLogs(); 230 | subscribe(processUrlIpByFlatMapMultipleThread()); 231 | break; 232 | } 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/transform/FlatMapOperatorFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator.transform; 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 | import android.widget.TextView; 9 | 10 | import com.chiclaim.rxjava.BaseFragment; 11 | import com.chiclaim.rxjava.R; 12 | 13 | import java.net.InetAddress; 14 | import java.net.MalformedURLException; 15 | import java.net.URL; 16 | import java.net.UnknownHostException; 17 | import java.util.List; 18 | 19 | import rx.Observable; 20 | import rx.Subscriber; 21 | import rx.android.schedulers.AndroidSchedulers; 22 | import rx.functions.Action1; 23 | import rx.functions.Func1; 24 | import rx.schedulers.Schedulers; 25 | 26 | /** 27 | * Created by chiclaim on 2016/03/23 28 | */ 29 | public class FlatMapOperatorFragment extends BaseFragment { 30 | 31 | private TextView tvLogs; 32 | 33 | @Nullable 34 | @Override 35 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 36 | return inflater.inflate(R.layout.fragment_flatmap_operator, container, false); 37 | } 38 | 39 | @Override 40 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 41 | super.onViewCreated(view, savedInstanceState); 42 | view.findViewById(R.id.btn_operator).setOnClickListener(this); 43 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 44 | } 45 | 46 | private Observable processUrlIpByOneFlatMap() { 47 | return Observable.just( 48 | "http://www.baidu.com/", 49 | "http://www.google.com/", 50 | "https://www.bing.com/") 51 | .flatMap(new Func1>() { 52 | @Override 53 | public Observable call(String s) { 54 | return createIpObservable(s); 55 | } 56 | }) 57 | .subscribeOn(Schedulers.io()) 58 | .observeOn(AndroidSchedulers.mainThread()); 59 | } 60 | 61 | 62 | private Observable processUrlIpByTwoFlatMap() { 63 | return Observable.just( 64 | "http://www.baidu.com/", 65 | "http://www.google.com/", 66 | "https://www.bing.com/") 67 | .toList()// if a Observable 68 | .flatMap(new Func1, Observable>() { 69 | @Override 70 | public Observable call(List s) { 71 | return Observable.from(s); 72 | } 73 | }) 74 | .flatMap(new Func1>() { 75 | @Override 76 | public Observable call(String s) { 77 | return createIpObservable(s); 78 | } 79 | }) 80 | .subscribeOn(Schedulers.io()) 81 | .observeOn(AndroidSchedulers.mainThread()); 82 | } 83 | 84 | private void returnIpByList() { 85 | processUrlIpByTwoFlatMap() 86 | .toList() //to list 87 | .subscribe(new Action1>() { 88 | @Override 89 | public void call(List s) { 90 | printLog(tvLogs, "Consume Data <- ", s.toString()); 91 | } 92 | }, new Action1() { 93 | @Override 94 | public void call(Throwable throwable) { 95 | printErrorLog(tvLogs, "throwable call()", throwable.getMessage()); 96 | } 97 | }); 98 | } 99 | 100 | private void returnIpOneByOne() { 101 | processUrlIpByTwoFlatMap() 102 | //processUrlIpByOneFlatMap() 103 | .subscribe(new Action1() { 104 | @Override 105 | public void call(String s) { 106 | printLog(tvLogs, "Consume Data <- ", s); 107 | } 108 | }, new Action1() { 109 | @Override 110 | public void call(Throwable throwable) { 111 | printErrorLog(tvLogs, "throwable call()", throwable.getMessage()); 112 | } 113 | }); 114 | } 115 | 116 | 117 | /** 118 | * 需求:获取urls的ip,返回所有urls的ips或者单个返回ip 119 | */ 120 | private void observableFlatMap() { 121 | //==============把ip作为list返回 122 | //returnIpByList(); 123 | //===============单个的返回 124 | returnIpOneByOne(); 125 | 126 | //@TODO 如果某个url获取ip失败,该url之后的url都不会去获取ip了.原因(官方注释): 127 | //If the Observable calls this method (onError), it will not thereafter call onNext or onCompleted. 128 | 129 | //@TODO 可以不调用subscriber.onError(e);或者调用subscriber.onNext(your value); 130 | } 131 | 132 | 133 | private String getIPByUrl(String str) throws MalformedURLException, UnknownHostException { 134 | URL urls = new URL(str); 135 | String host = urls.getHost(); 136 | String address = InetAddress.getByName(host).toString(); 137 | int b = address.indexOf("/"); 138 | return address.substring(b + 1); 139 | 140 | } 141 | 142 | 143 | private Observable createIpObservable(final String url) { 144 | return Observable.create(new Observable.OnSubscribe() { 145 | @Override 146 | public void call(Subscriber subscriber) { 147 | try { 148 | String ip = getIPByUrl(url); 149 | subscriber.onNext(ip); 150 | printLog(tvLogs, "Emit Data -> ", url + " : " + ip); 151 | } catch (MalformedURLException e) { 152 | e.printStackTrace(); 153 | //subscriber.onError(e); 154 | subscriber.onNext(null); 155 | } catch (UnknownHostException e) { 156 | e.printStackTrace(); 157 | //subscriber.onError(e); 158 | subscriber.onNext(null); 159 | } 160 | subscriber.onCompleted(); 161 | } 162 | }) 163 | .subscribeOn(Schedulers.io()); 164 | //.subscribeOn(Schedulers.io()) 注意该方法在这里调用和放在使用该Observable的地方调 产生不同的影响 165 | //把注释去掉会使用不同的线程去执行,放在放在使用该Observable的地方调会共用一个线程去执行 166 | } 167 | 168 | 169 | @Override 170 | public void onClick(View v) { 171 | switch (v.getId()) { 172 | case R.id.btn_operator: 173 | tvLogs.setText(""); 174 | observableFlatMap(); 175 | break; 176 | } 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /app/src/main/java/com/chiclaim/rxjava/operator/transform/MapOperatorFragment.java: -------------------------------------------------------------------------------- 1 | package com.chiclaim.rxjava.operator.transform; 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 | import android.widget.TextView; 9 | 10 | import com.chiclaim.rxjava.BaseFragment; 11 | import com.chiclaim.rxjava.R; 12 | 13 | import java.net.InetAddress; 14 | import java.net.MalformedURLException; 15 | import java.net.URL; 16 | import java.net.UnknownHostException; 17 | import java.util.Collections; 18 | import java.util.List; 19 | 20 | import rx.Observable; 21 | import rx.android.schedulers.AndroidSchedulers; 22 | import rx.functions.Action1; 23 | import rx.functions.Func1; 24 | import rx.schedulers.Schedulers; 25 | 26 | /** 27 | * Demonstrate map operator of RxJava
28 | * Created by chiclaim on 2016/03/23 29 | */ 30 | public class MapOperatorFragment extends BaseFragment { 31 | 32 | private TextView tvLogs; 33 | 34 | @Nullable 35 | @Override 36 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 37 | return inflater.inflate(R.layout.fragment_map_operator, container, false); 38 | } 39 | 40 | @Override 41 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 42 | super.onViewCreated(view, savedInstanceState); 43 | view.findViewById(R.id.btn_operator).setOnClickListener(this); 44 | tvLogs = (TextView) view.findViewById(R.id.tv_logs); 45 | tvLogs.setText("Click Button to test 'map operator'"); 46 | 47 | view.findViewById(R.id.btn_operator).setOnClickListener(this); 48 | view.findViewById(R.id.btn_operator_map_ips).setOnClickListener(this); 49 | 50 | } 51 | 52 | 53 | private String getIPByUrl(String str) throws MalformedURLException, UnknownHostException { 54 | URL urls = new URL(str); 55 | String host = urls.getHost(); 56 | String address = InetAddress.getByName(host).toString(); 57 | int b = address.indexOf("/"); 58 | return address.substring(b + 1); 59 | 60 | } 61 | 62 | 63 | private Observable processUrlsIpByMap() { 64 | return Observable.just( 65 | "http://www.baidu.com/",//invalid url 66 | "http://www.google.com/", 67 | "https://www.bing.com/") 68 | .map(new Func1() { 69 | @Override 70 | public String call(String s) { 71 | try { 72 | // if occur a exception how to notify to subscriber? you can use flatMap 73 | return s + " : " + getIPByUrl(s); 74 | } catch (MalformedURLException e) { 75 | e.printStackTrace(); 76 | } catch (UnknownHostException e) { 77 | e.printStackTrace(); 78 | } 79 | return null; 80 | } 81 | }) 82 | .subscribeOn(Schedulers.io()) 83 | .observeOn(AndroidSchedulers.mainThread()); 84 | } 85 | 86 | private void observableMapIps() { 87 | processUrlsIpByMap().subscribe(new Action1() { 88 | @Override 89 | public void call(String s) { 90 | printLog(tvLogs, "Consume Data: ", s); 91 | } 92 | }); 93 | } 94 | 95 | private void observableMapIpList() { 96 | processUrlsIpByMap().toList().subscribe(new Action1>() { 97 | @Override 98 | public void call(List s) { 99 | printLog(tvLogs, "Consume Data: ", s.toString()); 100 | } 101 | }); 102 | } 103 | 104 | 105 | private void observableMap() { 106 | Observable.from(new String[]{"This", "is", "RxJava"}) 107 | .map(new Func1() { 108 | @Override 109 | public String call(String s) { 110 | printLog(tvLogs, "Transform Data toUpperCase: ", s); 111 | return s.toUpperCase(); 112 | } 113 | }) 114 | .toList() 115 | .map(new Func1, List>() { 116 | @Override 117 | public List call(List strings) { 118 | printLog(tvLogs, "Transform Data Reverse List: ", strings.toString()); 119 | Collections.reverse(strings); 120 | return strings; 121 | } 122 | }) 123 | .observeOn(AndroidSchedulers.mainThread()) 124 | .subscribeOn(Schedulers.io()) 125 | .subscribe(new Action1>() { 126 | @Override 127 | public void call(List s) { 128 | printLog(tvLogs, "Consume Data ", s.toString()); 129 | } 130 | }); 131 | } 132 | 133 | @Override 134 | public void onClick(View v) { 135 | super.onClick(v); 136 | switch (v.getId()) { 137 | case R.id.btn_operator: 138 | tvLogs.setText(""); 139 | observableMap(); 140 | break; 141 | case R.id.btn_operator_map_ips: 142 | tvLogs.setText(""); 143 | observableMapIps(); 144 | //observableMapIpList(); 145 | break; 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 |