├── .gitignore ├── README.md ├── RxCache.iml ├── app ├── .gitignore ├── app.iml ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── cpoopc │ │ └── rxcache │ │ ├── ApplicationTest.java │ │ └── ObserveOnTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── cpoopc │ │ │ └── rxcache │ │ │ ├── App.java │ │ │ ├── MainActivity.java │ │ │ ├── api │ │ │ └── GithubService.java │ │ │ └── model │ │ │ └── User.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── cpoopc │ └── rxcache │ ├── ExampleUnitTest.java │ ├── Md5Test.java │ ├── OnsubscribeCacheNetTest.java │ ├── RxCacheResultTest.java │ └── UserTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── retrofit-rxcache ├── .gitignore ├── build.gradle ├── proguard-rules.pro ├── retrofit-rxcache.iml └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── cpoopc │ │ └── retrofitrxcache │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── cpoopc │ │ │ └── retrofitrxcache │ │ │ ├── AsyncOnSubscribeCacheNet.java │ │ │ ├── BasicCache.java │ │ │ ├── CacheNetOnSubscribeFactory.java │ │ │ ├── IRxCache.java │ │ │ ├── MD5.java │ │ │ ├── OnSubscribeCacheNet.java │ │ │ ├── RxCacheCallAdapterFactory.java │ │ │ ├── RxCacheHttpException.java │ │ │ ├── RxCacheResult.java │ │ │ └── SyncOnSubscribeCacheNet.java │ └── res │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── cpoopc │ └── retrofitrxcache │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | /.idea 8 | /.gradle -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RetrofitRxCache 2 | 3 | [![](https://jitpack.io/v/cpoopc/RetrofitRxCache.svg)](https://jitpack.io/#cpoopc/RetrofitRxCache) 4 | ### update node: 5 | 6 | 2016/9/1: 7 | 兼容升级到retrofit2.1.0 8 | 2016/5/15: 9 | RxCacheCallAdapterFactory create(IRxCache cachingSystem, boolean sync),sync指定同步获取缓存,网络还是异步获取 10 | 2016/2/28: 11 | 1. 更新到retrofit2-beta4版本,对应retrofit进行了点改动 12 | 2. 由注解方式(@UseRxCache)指定使用cache改为返回类型指定,返回类型为Observable>即可启用cache. 13 | 且可以根据RxCacheResult.isCache()判断是缓存还是网络返回结果. 14 | 15 | trans normal Observable into Observable with cache,support retrofit 16 | 17 | retrofit是个网络请求利器,帮助我们快速编写http请求.而且retrofit支持 RxJava,配合Rxjava实在十分强大. 18 | retrofit2.0之后,结构更加清晰,定制性更强了.此repo就是基于retrofit 2.0,为Observable提供了Cache支持. 19 | 接口方法加上@UseCache,即可实现Cache. 20 | 21 | ### cache的一些表现: 22 | 23 | 1. Cache获取与网络获取是异步进行的. 24 | 2. 若网络获取比Cache获取速度快,Cache不会发射出去. 25 | 3. 网络获取完毕后,异步进行保存Cache操作,不阻塞结果的发射. 26 | 27 | ### 引用方法 28 | 29 | 此lib加入了JitPack 30 | 引用方法 31 | 根目录下的build.gradle 32 | ``` 33 | allprojects { 34 | repositories { 35 | ... 36 | maven { url "https://jitpack.io" } 37 | } 38 | } 39 | ``` 40 | 项目中 41 | ``` 42 | 43 | dependencies { 44 | compile 'com.github.cpoopc:RetrofitRxCache:v1.0.5' 45 | } 46 | 47 | 48 | ``` 49 | 50 | ### Usage 51 | 52 | ``` 53 | 54 | Retrofit retrofit = new Retrofit.Builder() 55 | .baseUrl("https://api.github.com") 56 | .addCallAdapterFactory(RxCacheCallAdapterFactory.create(BasicCache.fromCtx(this), false))// 分开读取缓存,网络 57 | // .addCallAdapterFactory(RxCacheCallAdapterFactory.create(BasicCache.fromCtx(this), true))// 先读取缓存,再获取网络 58 | .addConverterFactory(GsonConverterFactory.create()) 59 | .build(); 60 | 61 | public interface GithubService { 62 | 63 | @GET("users/{username}") 64 | Observable userDetail(@Path("username") String userName); // Observable泛型为RxCacheResult,即可使用cache 65 | 66 | } 67 | 68 | ``` 69 | -------------------------------------------------------------------------------- /RxCache.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.1" 6 | 7 | defaultConfig { 8 | applicationId "com.cpoopc.rxcache" 9 | minSdkVersion 12 10 | targetSdkVersion 21 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | def retrofit_version = '2.0.0-beta4' // 2.0.0-beta4 23 | 24 | dependencies { 25 | compile fileTree(dir: 'libs', include: ['*.jar']) 26 | testCompile 'junit:junit:4.12' 27 | testCompile "org.robolectric:robolectric:3.0" 28 | compile 'com.android.support:appcompat-v7:23.+' 29 | compile 'com.android.support:support-v4:23.+' 30 | compile project(':retrofit-rxcache') 31 | provided 'com.squareup.retrofit2:retrofit:' + retrofit_version 32 | compile 'com.squareup.retrofit2:converter-gson:' + retrofit_version 33 | compile 'io.reactivex:rxandroid:1.0.1' 34 | 35 | compile 'com.github.bumptech.glide:glide:3.6.1' 36 | compile 'com.jakewharton:butterknife:7.0.1' 37 | 38 | } 39 | -------------------------------------------------------------------------------- /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 E:\Android\adt-bundle-windows-x86-20131030\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/cpoopc/rxcache/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 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/androidTest/java/com/cpoopc/rxcache/ObserveOnTest.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 2 | 3 | import android.test.AndroidTestCase; 4 | 5 | import java.util.concurrent.CountDownLatch; 6 | import java.util.concurrent.TimeUnit; 7 | import java.util.concurrent.atomic.AtomicInteger; 8 | 9 | import javax.security.auth.Subject; 10 | 11 | import rx.Observable; 12 | import rx.Subscriber; 13 | import rx.android.schedulers.AndroidSchedulers; 14 | import rx.schedulers.Schedulers; 15 | import rx.subjects.PublishSubject; 16 | 17 | 18 | /** 19 | * @author cpoopc 20 | * @date 2016/1/18 21 | * @time 18:51 22 | * @description 23 | */ 24 | public class ObserveOnTest extends AndroidTestCase{ 25 | 26 | private static class MokeException extends RuntimeException { 27 | public MokeException(String detailMessage) { 28 | super(detailMessage); 29 | } 30 | } 31 | 32 | public void testObserveOnAndroidMainThread() throws InterruptedException { 33 | final CountDownLatch completedLatch = new CountDownLatch(1); 34 | final AtomicInteger atomicInteger = new AtomicInteger(0); 35 | final int count = 20; 36 | Observable.create(new Observable.OnSubscribe() { 37 | @Override 38 | public void call(Subscriber subscriber) { 39 | subscriber.onNext(count); 40 | // try { 41 | // Thread.sleep(1000); 42 | // } catch (InterruptedException e) { 43 | // e.printStackTrace(); 44 | // } 45 | // 46 | // subscriber.onError(new MokeException("moke exception")); 47 | } 48 | }) 49 | .subscribeOn(Schedulers.newThread()) 50 | .observeOn(Schedulers.newThread()) 51 | .subscribe(new Subscriber() { 52 | @Override 53 | public void onCompleted() { 54 | 55 | } 56 | 57 | @Override 58 | public void onError(Throwable e) { 59 | System.out.println("onError:" + atomicInteger.get()); 60 | android.util.Log.e("cc:", "onError:" + atomicInteger.get()); 61 | assertEquals(atomicInteger.get(), count); 62 | completedLatch.countDown(); 63 | } 64 | 65 | @Override 66 | public void onNext(Integer o) { 67 | android.util.Log.e("cc:", "onNext:" + o); 68 | System.out.println("onNext:" + o); 69 | atomicInteger.getAndSet(o); 70 | completedLatch.countDown(); 71 | } 72 | }); 73 | completedLatch.await(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/java/com/cpoopc/rxcache/App.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 2 | 3 | import android.app.Application; 4 | 5 | import com.cpoopc.rxcache.api.GithubService; 6 | 7 | import com.cpoopc.retrofitrxcache.BasicCache; 8 | import retrofit2.Retrofit; 9 | import com.cpoopc.retrofitrxcache.RxCacheCallAdapterFactory; 10 | import retrofit2.converter.gson.GsonConverterFactory; 11 | 12 | /** 13 | * User: cpoopc 14 | * Date: 2016-01-18 15 | * Time: 13:53 16 | * Ver.: 0.1 17 | */ 18 | public class App extends Application { 19 | 20 | private static App instance; 21 | private Retrofit mRetrofit; 22 | private GithubService mGithubService; 23 | 24 | public static App getInstance() { 25 | return instance; 26 | } 27 | 28 | @Override 29 | public void onCreate() { 30 | super.onCreate(); 31 | instance = this; 32 | mRetrofit = new Retrofit.Builder() 33 | .baseUrl("https://api.github.com") 34 | .addCallAdapterFactory(RxCacheCallAdapterFactory.create(BasicCache.fromCtx(this), false))// 分开读取缓存,网络 35 | // .addCallAdapterFactory(RxCacheCallAdapterFactory.create(BasicCache.fromCtx(this), true))// 先读取缓存,再获取网络 36 | .addConverterFactory(GsonConverterFactory.create()) 37 | .build(); 38 | } 39 | 40 | public GithubService getGithubService() { 41 | if (mGithubService == null) { 42 | mGithubService = mRetrofit.create(GithubService.class); 43 | } 44 | return mGithubService; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/com/cpoopc/rxcache/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.util.Log; 6 | import android.view.View; 7 | import android.widget.ImageView; 8 | import android.widget.TextView; 9 | 10 | import com.bumptech.glide.Glide; 11 | import com.cpoopc.retrofitrxcache.RxCacheResult; 12 | import com.cpoopc.rxcache.model.User; 13 | 14 | import butterknife.Bind; 15 | import butterknife.ButterKnife; 16 | import rx.Observable; 17 | import rx.Subscriber; 18 | import rx.android.schedulers.AndroidSchedulers; 19 | import rx.functions.Func1; 20 | import rx.schedulers.Schedulers; 21 | 22 | public class MainActivity extends Activity { 23 | 24 | @Bind(R.id.avatarIv) 25 | ImageView mAvatarIv; 26 | @Bind(R.id.userNameTv) 27 | TextView mUserNameTv; 28 | @Bind(R.id.companyTv) 29 | TextView mCompanyTv; 30 | @Bind(R.id.locationTv) 31 | TextView mLocationTv; 32 | @Bind(R.id.createAtTv) 33 | TextView mCreateAtTv; 34 | @Bind(R.id.followersCountTv) 35 | TextView mFollowersCountTv; 36 | @Bind(R.id.starredCountTv) 37 | TextView mStarredCountTv; 38 | @Bind(R.id.followingCountTv) 39 | TextView mFollowingCountTv; 40 | 41 | @Override 42 | protected void onCreate(Bundle savedInstanceState) { 43 | super.onCreate(savedInstanceState); 44 | setContentView(R.layout.activity_main); 45 | ButterKnife.bind(this); 46 | getUserDetail(); 47 | mUserNameTv.setOnClickListener(new View.OnClickListener() { 48 | @Override 49 | public void onClick(View v) { 50 | Log.e("cp:", "onclick"); 51 | getUserDetail(); 52 | 53 | } 54 | }); 55 | 56 | } 57 | 58 | @Override 59 | protected void onDestroy() { 60 | super.onDestroy(); 61 | ButterKnife.unbind(this); 62 | } 63 | 64 | public void getUserDetail() { 65 | Observable> userObservable = App.getInstance().getGithubService().userDetail("cpoopc"); 66 | userObservable 67 | .subscribeOn(Schedulers.io()) 68 | .materialize() 69 | .observeOn(AndroidSchedulers.mainThread()) 70 | .>dematerialize() 71 | .subscribe(new Subscriber>() { 72 | @Override 73 | public void onCompleted() { 74 | Log.e("cp:", "onCompleted"); 75 | } 76 | 77 | @Override 78 | public void onError(Throwable e) { 79 | Log.e("cp:", "onError:" + e.getMessage()); 80 | } 81 | 82 | @Override 83 | public void onNext(RxCacheResult user) { 84 | Log.e("cp:", user.isCache() + " onNext:" + user.getResultModel()); 85 | bindUser(user.getResultModel()); 86 | } 87 | 88 | }); 89 | 90 | } 91 | 92 | 93 | private void bindUser(User user) { 94 | if (user != null) { 95 | Glide.with(this).load(user.getAvatar_url()).into(mAvatarIv); 96 | mUserNameTv.setText(user.getLogin()); 97 | mCompanyTv.setText(user.getCompany()); 98 | mLocationTv.setText(user.getLocation()); 99 | mCreateAtTv.setText(user.getCreated_at()); 100 | mFollowersCountTv.setText(String.valueOf(user.getFollowers())); 101 | mStarredCountTv.setText("?"); 102 | mFollowingCountTv.setText(String.valueOf(user.getFollowing())); 103 | } else { 104 | mAvatarIv.setImageResource(R.mipmap.ic_launcher); 105 | mUserNameTv.setText("?"); 106 | mCompanyTv.setText("?"); 107 | mLocationTv.setText("?"); 108 | mCreateAtTv.setText("?"); 109 | mFollowersCountTv.setText("?"); 110 | mStarredCountTv.setText("?"); 111 | mFollowingCountTv.setText("?"); 112 | } 113 | 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /app/src/main/java/com/cpoopc/rxcache/api/GithubService.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache.api; 2 | 3 | 4 | import com.cpoopc.retrofitrxcache.RxCacheResult; 5 | import com.cpoopc.rxcache.model.User; 6 | 7 | import retrofit2.http.GET; 8 | import retrofit2.http.Path; 9 | import rx.Observable; 10 | 11 | /** 12 | * User: cpoopc 13 | * Date: 2016-01-18 14 | * Time: 13:47 15 | * Ver.: 0.1 16 | */ 17 | public interface GithubService { 18 | 19 | @GET("users/{username}") 20 | Observable> userDetail(@Path("username") String userName); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /app/src/main/java/com/cpoopc/rxcache/model/User.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache.model; 2 | 3 | /** 4 | * User: cpoopc 5 | * Date: 2016-01-18 6 | * Time: 13:47 7 | * Ver.: 0.1 8 | */ 9 | public class User { 10 | 11 | public String login; 12 | public int id; 13 | public String avatar_url; 14 | public String url; 15 | public String name; 16 | public String company; 17 | public String blog; 18 | public String location; 19 | public String email; 20 | public int public_repos; 21 | public int public_gists; 22 | public int followers; 23 | public int following; 24 | public String created_at; 25 | public String updated_at; 26 | 27 | public String getLogin() { 28 | return login; 29 | } 30 | 31 | public void setLogin(String login) { 32 | this.login = login; 33 | } 34 | 35 | public int getId() { 36 | return id; 37 | } 38 | 39 | public void setId(int id) { 40 | this.id = id; 41 | } 42 | 43 | public String getAvatar_url() { 44 | return avatar_url; 45 | } 46 | 47 | public void setAvatar_url(String avatar_url) { 48 | this.avatar_url = avatar_url; 49 | } 50 | 51 | public String getUrl() { 52 | return url; 53 | } 54 | 55 | public void setUrl(String url) { 56 | this.url = url; 57 | } 58 | 59 | public String getName() { 60 | return name; 61 | } 62 | 63 | public void setName(String name) { 64 | this.name = name; 65 | } 66 | 67 | public String getCompany() { 68 | return company; 69 | } 70 | 71 | public void setCompany(String company) { 72 | this.company = company; 73 | } 74 | 75 | public String getBlog() { 76 | return blog; 77 | } 78 | 79 | public void setBlog(String blog) { 80 | this.blog = blog; 81 | } 82 | 83 | public String getLocation() { 84 | return location; 85 | } 86 | 87 | public void setLocation(String location) { 88 | this.location = location; 89 | } 90 | 91 | public String getEmail() { 92 | return email; 93 | } 94 | 95 | public void setEmail(String email) { 96 | this.email = email; 97 | } 98 | 99 | public int getPublic_repos() { 100 | return public_repos; 101 | } 102 | 103 | public void setPublic_repos(int public_repos) { 104 | this.public_repos = public_repos; 105 | } 106 | 107 | public int getPublic_gists() { 108 | return public_gists; 109 | } 110 | 111 | public void setPublic_gists(int public_gists) { 112 | this.public_gists = public_gists; 113 | } 114 | 115 | public int getFollowers() { 116 | return followers; 117 | } 118 | 119 | public void setFollowers(int followers) { 120 | this.followers = followers; 121 | } 122 | 123 | public int getFollowing() { 124 | return following; 125 | } 126 | 127 | public void setFollowing(int following) { 128 | this.following = following; 129 | } 130 | 131 | public String getCreated_at() { 132 | return created_at; 133 | } 134 | 135 | public void setCreated_at(String created_at) { 136 | this.created_at = created_at; 137 | } 138 | 139 | public String getUpdated_at() { 140 | return updated_at; 141 | } 142 | 143 | public void setUpdated_at(String updated_at) { 144 | this.updated_at = updated_at; 145 | } 146 | 147 | @Override 148 | public String toString() { 149 | return "User{" + 150 | "login='" + login + '\'' + 151 | ", id=" + id + 152 | ", avatar_url='" + avatar_url + '\'' + 153 | ", url='" + url + '\'' + 154 | ", name='" + name + '\'' + 155 | ", company='" + company + '\'' + 156 | ", blog='" + blog + '\'' + 157 | ", location='" + location + '\'' + 158 | ", email='" + email + '\'' + 159 | ", public_repos=" + public_repos + 160 | ", public_gists=" + public_gists + 161 | ", followers=" + followers + 162 | ", following=" + following + 163 | ", created_at='" + created_at + '\'' + 164 | ", updated_at='" + updated_at + '\'' + 165 | '}'; 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 18 | 19 | 26 | 27 | 34 | 35 | 42 | 43 | 49 | 50 | 56 | 57 | 63 | 64 | 71 | 72 | 77 | 78 | 84 | 85 | 93 | 94 | 98 | 99 | 100 | 106 | 107 | 115 | 116 | 120 | 121 | 122 | 128 | 129 | 137 | 138 | 142 | 143 | 144 | 145 | 152 | 153 | 154 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpoopc/RetrofitRxCache/be8c81a366cc4e41e8b85ad017f723257264f0d8/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpoopc/RetrofitRxCache/be8c81a366cc4e41e8b85ad017f723257264f0d8/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpoopc/RetrofitRxCache/be8c81a366cc4e41e8b85ad017f723257264f0d8/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpoopc/RetrofitRxCache/be8c81a366cc4e41e8b85ad017f723257264f0d8/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpoopc/RetrofitRxCache/be8c81a366cc4e41e8b85ad017f723257264f0d8/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | RxCache 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/cpoopc/rxcache/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /app/src/test/java/com/cpoopc/rxcache/Md5Test.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 2 | 3 | import com.cpoopc.retrofitrxcache.MD5; 4 | 5 | import junit.framework.Assert; 6 | 7 | import org.junit.After; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.robolectric.RobolectricGradleTestRunner; 12 | import org.robolectric.annotation.Config; 13 | 14 | /** 15 | * @author cpoopc 16 | * @date 2016/06/29 17 | * @time 22:53 18 | * @description 19 | */ 20 | @RunWith(RobolectricGradleTestRunner.class) 21 | @Config(constants = BuildConfig.class) 22 | public class Md5Test { 23 | 24 | @Before 25 | public void setUp() { 26 | 27 | } 28 | 29 | @After 30 | public void tearDown() { 31 | 32 | } 33 | 34 | @Test 35 | public void testMd5() { 36 | String content = "待测文本"; 37 | Assert.assertEquals(MD5.getMD5(content),MD5.getMD5(content)); 38 | Assert.assertNotSame(MD5.getMD5(content), MD5.getMD5(content + '1')); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/src/test/java/com/cpoopc/rxcache/OnsubscribeCacheNetTest.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 2 | 3 | import android.support.annotation.NonNull; 4 | 5 | import com.cpoopc.retrofitrxcache.AsyncOnSubscribeCacheNet; 6 | import com.cpoopc.retrofitrxcache.CacheNetOnSubscribeFactory; 7 | import com.cpoopc.retrofitrxcache.OnSubscribeCacheNet; 8 | 9 | 10 | import org.junit.After; 11 | import org.junit.Assert; 12 | import org.junit.Before; 13 | import org.junit.FixMethodOrder; 14 | import org.junit.Test; 15 | import org.junit.runner.RunWith; 16 | import org.junit.runners.MethodSorters; 17 | import org.robolectric.RobolectricGradleTestRunner; 18 | import org.robolectric.annotation.Config; 19 | 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | import java.util.concurrent.CountDownLatch; 23 | 24 | import rx.Observable; 25 | import rx.Subscriber; 26 | import rx.functions.Action1; 27 | 28 | /** 29 | * @author cpoopc 30 | * @date 2016/06/29 31 | * @time 22:53 32 | * @description 33 | */ 34 | @RunWith(RobolectricGradleTestRunner.class) 35 | @Config(constants = BuildConfig.class) 36 | @FixMethodOrder(MethodSorters.DEFAULT) 37 | public class OnsubscribeCacheNetTest { 38 | 39 | public final String TAG = "OnsubscribeCacheNetTest"; 40 | 41 | @Before 42 | public void setUp() { 43 | } 44 | 45 | @After 46 | public void tearDown() { 47 | 48 | } 49 | 50 | @Test 51 | public void testAsyncSequence() throws InterruptedException { 52 | Observable observableShort = createShortObservable(); 53 | Observable observableLong = createLongObservable(); 54 | final CountDownLatch countDownLatch = new CountDownLatch(1); 55 | final List resultList = new ArrayList<>(); 56 | Observable.create(new CacheNetOnSubscribeFactory(false).create(observableShort, observableLong, new Action1() { 57 | @Override 58 | public void call(String s) { 59 | android.util.Log.d(TAG, "cache action : " + s); 60 | System.out.println("cache action : " + s); 61 | Assert.assertNotNull(s); 62 | } 63 | })).subscribe(new Subscriber() { 64 | @Override 65 | public void onCompleted() { 66 | android.util.Log.d(TAG, "onCompleted " ); 67 | System.out.println("onCompleted " ); 68 | countDownLatch.countDown(); 69 | } 70 | 71 | @Override 72 | public void onError(Throwable e) { 73 | android.util.Log.d(TAG, "onError : " + e); 74 | System.out.println("onError : " + e); 75 | countDownLatch.countDown(); 76 | } 77 | 78 | @Override 79 | public void onNext(String s) { 80 | android.util.Log.d(TAG, "onNext : " + s); 81 | resultList.add(s); 82 | System.out.println("onNext : " + s); 83 | } 84 | }); 85 | countDownLatch.await(); 86 | Assert.assertEquals(2,resultList.size()); 87 | Assert.assertEquals("short", resultList.get(0)); 88 | Assert.assertEquals("long", resultList.get(1)); 89 | } 90 | 91 | @Test 92 | public void testAsyncReverseSequence() throws InterruptedException { 93 | Observable observableShort = createShortObservable(); 94 | Observable observableLong = createLongObservable(); 95 | final CountDownLatch countDownLatch = new CountDownLatch(1); 96 | final List resultList = new ArrayList<>(); 97 | Observable.create(new AsyncOnSubscribeCacheNet(observableLong, observableShort, new Action1() { 98 | @Override 99 | public void call(String s) { 100 | android.util.Log.d(TAG, "cache action : " + s); 101 | System.out.println("cache action : " + s); 102 | Assert.assertNotNull(s); 103 | } 104 | })).subscribe(new Subscriber() { 105 | @Override 106 | public void onCompleted() { 107 | android.util.Log.d(TAG, "onCompleted "); 108 | System.out.println("onCompleted "); 109 | countDownLatch.countDown(); 110 | } 111 | 112 | @Override 113 | public void onError(Throwable e) { 114 | android.util.Log.d(TAG, "onError : " + e); 115 | System.out.println("onError : " + e); 116 | countDownLatch.countDown(); 117 | } 118 | 119 | @Override 120 | public void onNext(String s) { 121 | android.util.Log.d(TAG, "onNext : " + s); 122 | resultList.add(s); 123 | System.out.println("onNext : " + s); 124 | } 125 | }); 126 | countDownLatch.await(); 127 | Assert.assertEquals(1,resultList.size());// 当网络的先返回,就不会再发射缓存Observable内容 128 | Assert.assertEquals("short", resultList.get(0)); 129 | } 130 | 131 | @Test 132 | public void testAsyncOnError() throws InterruptedException { 133 | Observable errorObservable = Observable.create(new Observable.OnSubscribe() { 134 | @Override 135 | public void call(Subscriber subscriber) { 136 | subscriber.onError(new NullPointerException("测试错误")); 137 | } 138 | }); 139 | final CountDownLatch countDownLatch = new CountDownLatch(1); 140 | Observable.create(new CacheNetOnSubscribeFactory(true).create(errorObservable, createShortObservable(), new Action1() { 141 | @Override 142 | public void call(String s) { 143 | 144 | } 145 | })).subscribe(new Subscriber() { 146 | @Override 147 | public void onCompleted() { 148 | System.out.println("完成"); 149 | countDownLatch.countDown(); 150 | } 151 | 152 | @Override 153 | public void onError(Throwable e) { 154 | Assert.assertNull(e); 155 | } 156 | 157 | @Override 158 | public void onNext(String s) { 159 | System.out.println(s); 160 | Assert.assertEquals(s,"short"); 161 | } 162 | }); 163 | countDownLatch.await(); 164 | 165 | } 166 | 167 | @Test 168 | public void testSyncSequence() throws InterruptedException { 169 | Observable observableShort = createShortObservable(); 170 | Observable observableLong = createLongObservable(); 171 | final CountDownLatch countDownLatch = new CountDownLatch(1); 172 | final List resultList = new ArrayList<>(); 173 | Observable.create(new OnSubscribeCacheNet(observableShort, observableLong, new Action1() { 174 | @Override 175 | public void call(String s) { 176 | android.util.Log.d(TAG, "cache action : " + s); 177 | System.out.println("cache action : " + s); 178 | Assert.assertNotNull(s); 179 | } 180 | })).subscribe(new Subscriber() { 181 | @Override 182 | public void onCompleted() { 183 | android.util.Log.d(TAG, "onCompleted " ); 184 | System.out.println("onCompleted " ); 185 | countDownLatch.countDown(); 186 | } 187 | 188 | @Override 189 | public void onError(Throwable e) { 190 | android.util.Log.d(TAG, "onError : " + e); 191 | System.out.println("onError : " + e); 192 | countDownLatch.countDown(); 193 | } 194 | 195 | @Override 196 | public void onNext(String s) { 197 | android.util.Log.d(TAG, "onNext : " + s); 198 | resultList.add(s); 199 | System.out.println("onNext : " + s); 200 | } 201 | }); 202 | countDownLatch.await(); 203 | Assert.assertEquals(2,resultList.size()); 204 | Assert.assertEquals("short", resultList.get(0)); 205 | Assert.assertEquals("long", resultList.get(1)); 206 | } 207 | 208 | @Test 209 | public void testSyncReverseSequence() throws InterruptedException { 210 | Observable observableShort = createShortObservable(); 211 | Observable observableLong = createLongObservable(); 212 | final CountDownLatch countDownLatch = new CountDownLatch(1); 213 | final List resultList = new ArrayList<>(); 214 | Observable.create(new OnSubscribeCacheNet(observableLong, observableShort, new Action1() { 215 | @Override 216 | public void call(String s) { 217 | android.util.Log.d(TAG, "cache action : " + s); 218 | System.out.println("cache action : " + s); 219 | Assert.assertNotNull(s); 220 | } 221 | })).subscribe(new Subscriber() { 222 | @Override 223 | public void onCompleted() { 224 | android.util.Log.d(TAG, "onCompleted "); 225 | System.out.println("onCompleted "); 226 | countDownLatch.countDown(); 227 | } 228 | 229 | @Override 230 | public void onError(Throwable e) { 231 | android.util.Log.d(TAG, "onError : " + e); 232 | System.out.println("onError : " + e); 233 | countDownLatch.countDown(); 234 | } 235 | 236 | @Override 237 | public void onNext(String s) { 238 | android.util.Log.d(TAG, "onNext : " + s); 239 | resultList.add(s); 240 | System.out.println("onNext : " + s); 241 | } 242 | }); 243 | countDownLatch.await(); 244 | Assert.assertEquals(2,resultList.size());// 当网络的先返回,就不会再发射缓存Observable内容 245 | Assert.assertEquals("long", resultList.get(0)); 246 | Assert.assertEquals("short", resultList.get(1)); 247 | } 248 | 249 | @NonNull 250 | private Observable createLongObservable() { 251 | return Observable.create(new Observable.OnSubscribe() { 252 | @Override 253 | public void call(Subscriber subscriber) { 254 | try { 255 | Thread.sleep(2000); 256 | subscriber.onNext("long"); 257 | subscriber.onCompleted(); 258 | } catch (InterruptedException e) { 259 | e.printStackTrace(); 260 | subscriber.onError(e); 261 | } 262 | } 263 | }); 264 | } 265 | 266 | @NonNull 267 | private Observable createShortObservable() { 268 | return Observable.create(new Observable.OnSubscribe() { 269 | @Override 270 | public void call(Subscriber subscriber) { 271 | try { 272 | Thread.sleep(1000); 273 | subscriber.onNext("short"); 274 | subscriber.onCompleted(); 275 | } catch (InterruptedException e) { 276 | e.printStackTrace(); 277 | subscriber.onError(e); 278 | } 279 | } 280 | }); 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /app/src/test/java/com/cpoopc/rxcache/RxCacheResultTest.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 2 | 3 | import com.cpoopc.retrofitrxcache.RxCacheResult; 4 | 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.robolectric.RobolectricGradleTestRunner; 9 | import org.robolectric.annotation.Config; 10 | 11 | /** 12 | * @author cpoopc 13 | * @date 2016/06/29 14 | * @time 22:53 15 | * @description 16 | */ 17 | @RunWith(RobolectricGradleTestRunner.class) 18 | @Config(constants = BuildConfig.class) 19 | public class RxCacheResultTest { 20 | 21 | @Test 22 | public void testResult() { 23 | RxCacheResult rxCacheResult = new RxCacheResult(true, "哈哈"); 24 | Assert.assertNotNull(rxCacheResult); 25 | Assert.assertTrue(rxCacheResult.isCache()); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /app/src/test/java/com/cpoopc/rxcache/UserTest.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.rxcache; 2 | 3 | import com.cpoopc.rxcache.model.User; 4 | 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.robolectric.RobolectricGradleTestRunner; 9 | import org.robolectric.annotation.Config; 10 | 11 | /** 12 | * @author cpoopc 13 | * @date 2016/06/29 14 | * @time 22:53 15 | * @description 16 | */ 17 | @RunWith(RobolectricGradleTestRunner.class) 18 | @Config(constants = BuildConfig.class) 19 | public class UserTest { 20 | 21 | @Test 22 | public void testUser() { 23 | User user = new User(); 24 | Assert.assertNotNull(user); 25 | user.setBlog("blog"); 26 | Assert.assertNotNull(user.getBlog()); 27 | Assert.assertEquals(user.getBlog(),"blog"); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" } 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:1.5.0' 10 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2' 11 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | jcenter() 20 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" } 21 | } 22 | } 23 | 24 | //task clean(type: Delete) { 25 | // delete rootProject.buildDir 26 | //} 27 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpoopc/RetrofitRxCache/be8c81a366cc4e41e8b85ad017f723257264f0d8/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Jan 18 11:49:47 CST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /retrofit-rxcache/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /retrofit-rxcache/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.1" 6 | 7 | defaultConfig { 8 | minSdkVersion 12 9 | targetSdkVersion 23 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | testCompile 'junit:junit:4.12' 24 | compile 'com.jakewharton:disklrucache:2.0.2' 25 | provided 'com.squareup.retrofit2:retrofit:2.1.0' 26 | provided 'io.reactivex:rxandroid:1.0.1' 27 | } 28 | 29 | 30 | apply plugin: 'com.github.dcendents.android-maven' 31 | apply plugin: 'com.jfrog.bintray' 32 | // library版本 33 | version = "v1.0.5" 34 | 35 | def siteUrl = 'https://github.com/cpoopc/RetrofitRxCache' // 项目的主页 36 | def gitUrl = 'https://github.com/cpoopc/RetrofitRxCache.git' // Git仓库的url 37 | def projectName = "RetrofitRxCache" 38 | group = 'com.github.cpoopc' // Maven Group ID for the artifact,一般填你唯一的包名 39 | 40 | install { 41 | repositories.mavenInstaller { 42 | // This generates POM.xml with proper parameters 43 | pom { 44 | project { 45 | packaging 'aar' 46 | // Add your description here 47 | name 'trans normal Observable into Observable with cache,support retrofit' //项目描述 48 | url siteUrl 49 | // Set your license 50 | licenses { 51 | license { 52 | name 'The Apache Software License, Version 2.0' 53 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 54 | } 55 | } 56 | developers { 57 | developer { 58 | id 'cpoopc' //填写开发者基本信息 59 | name 'cp' 60 | email '303727604@qq.com' 61 | } 62 | } 63 | scm { 64 | connection gitUrl 65 | developerConnection gitUrl 66 | url siteUrl 67 | } 68 | } 69 | } 70 | } 71 | } 72 | task sourcesJar(type: Jar) { 73 | from android.sourceSets.main.java.srcDirs 74 | classifier = 'sources' 75 | } 76 | task javadoc(type: Javadoc) { 77 | source = android.sourceSets.main.java.srcDirs 78 | classpath += configurations.compile 79 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 80 | } 81 | task javadocJar(type: Jar, dependsOn: javadoc) { 82 | classifier = 'javadoc' 83 | from javadoc.destinationDir 84 | } 85 | javadoc { 86 | options{ 87 | encoding "UTF-8" 88 | charSet 'UTF-8' 89 | author true 90 | version true 91 | links "http://docs.oracle.com/javase/7/docs/api" 92 | title projectName 93 | } 94 | } 95 | 96 | artifacts { 97 | archives javadocJar 98 | archives sourcesJar 99 | } 100 | Properties properties = new Properties() 101 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 102 | bintray { 103 | user = properties.getProperty("bintray.user") 104 | key = properties.getProperty("bintray.apikey") 105 | configurations = ['archives'] 106 | pkg { 107 | repo = "maven" //发布到Bintray的那个仓库里,默认账户有四个库,我们这里上传到maven库 108 | name = projectName //发布到Bintray上的项目名字 109 | websiteUrl = siteUrl 110 | vcsUrl = gitUrl 111 | licenses = ["Apache-2.0"] 112 | publish = true 113 | } 114 | } -------------------------------------------------------------------------------- /retrofit-rxcache/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in E:\Android\adt-bundle-windows-x86-20131030\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 | -------------------------------------------------------------------------------- /retrofit-rxcache/retrofit-rxcache.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/androidTest/java/com/cpoopc/retrofitrxcache/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 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 | } -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/AsyncOnSubscribeCacheNet.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | 4 | import android.util.Log; 5 | 6 | import java.util.concurrent.CountDownLatch; 7 | 8 | import rx.Observable; 9 | import rx.Subscriber; 10 | import rx.functions.Action1; 11 | import rx.schedulers.Schedulers; 12 | 13 | /** 14 | * 缓存+网络请求 15 | * User: cpoopc 16 | * Date: 2016-01-18 17 | * Time: 10:19 18 | * Ver.: 0.1 19 | */ 20 | public class AsyncOnSubscribeCacheNet implements Observable.OnSubscribe { 21 | 22 | private final boolean debug = true; 23 | private final String TAG = "OnSubscribeCacheNet:"; 24 | 25 | // 读取缓存 26 | protected ObservableWrapper cacheObservable; 27 | 28 | // 读取网络 29 | protected ObservableWrapper netObservable; 30 | 31 | // 网络读取完毕,缓存动作 32 | protected Action1 storeCacheAction; 33 | 34 | protected CountDownLatch cacheLatch = new CountDownLatch(1); 35 | protected CountDownLatch netLatch = new CountDownLatch(1); 36 | 37 | public AsyncOnSubscribeCacheNet(Observable cacheObservable, Observable netObservable, Action1 storeCacheAction) { 38 | this.cacheObservable = new ObservableWrapper(cacheObservable); 39 | this.netObservable = new ObservableWrapper(netObservable); 40 | this.storeCacheAction = storeCacheAction; 41 | } 42 | 43 | @Override 44 | public void call(Subscriber subscriber) { 45 | cacheObservable.getObservable().subscribeOn(Schedulers.io()).unsafeSubscribe(new CacheObserver(cacheObservable, subscriber, storeCacheAction)); 46 | netObservable.getObservable().subscribeOn(Schedulers.io()).unsafeSubscribe(new NetObserver(netObservable, subscriber, storeCacheAction)); 47 | } 48 | 49 | class ObservableWrapper { 50 | 51 | Observable observable; 52 | T data; 53 | 54 | public ObservableWrapper(Observable observable) { 55 | this.observable = observable; 56 | } 57 | 58 | public Observable getObservable() { 59 | return observable; 60 | } 61 | 62 | public T getData() { 63 | return data; 64 | } 65 | 66 | public void setData(T data) { 67 | this.data = data; 68 | } 69 | } 70 | 71 | class NetObserver extends Subscriber { 72 | 73 | ObservableWrapper observableWrapper; 74 | Subscriber subscriber; 75 | Action1 storeCacheAction; 76 | 77 | public NetObserver(ObservableWrapper observableWrapper, Subscriber subscriber, Action1 storeCacheAction) { 78 | this.observableWrapper = observableWrapper; 79 | this.subscriber = subscriber; 80 | this.storeCacheAction = storeCacheAction; 81 | } 82 | 83 | @Override 84 | public void onCompleted() { 85 | if (debug) Log.i(TAG, "net onCompleted "); 86 | try { 87 | if (storeCacheAction != null) { 88 | logThread("保存到本地缓存 "); 89 | storeCacheAction.call(observableWrapper.getData()); 90 | } 91 | } catch (Exception e) { 92 | onError(e); 93 | } 94 | if (subscriber != null && !subscriber.isUnsubscribed()) { 95 | subscriber.onCompleted(); 96 | } 97 | netLatch.countDown(); 98 | } 99 | 100 | @Override 101 | public void onError(Throwable e) { 102 | if (debug) Log.e(TAG, "net onError "); 103 | try { 104 | if (debug) Log.e(TAG, "net onError await if cache not completed."); 105 | cacheLatch.await(); 106 | if (debug) Log.e(TAG, "net onError await over."); 107 | } catch (InterruptedException e1) { 108 | e1.printStackTrace(); 109 | } 110 | if (subscriber != null && !subscriber.isUnsubscribed()) { 111 | subscriber.onError(e); 112 | } 113 | } 114 | 115 | @Override 116 | public void onNext(T o) { 117 | if (debug) Log.i(TAG, "net onNext o:" + o); 118 | observableWrapper.setData(o); 119 | logThread(""); 120 | if (debug) Log.e(TAG, " check subscriber :" + subscriber + " isUnsubscribed:" + subscriber.isUnsubscribed()); 121 | if (subscriber != null && !subscriber.isUnsubscribed()) { 122 | subscriber.onNext(o);// FIXME: issue A:外面如果ObservableOn 其他线程,将会是异步操作,如果在实际的onNext调用之前,发生了onComplete或者onError,将会unsubscribe,导致onNext没有被调用 123 | } 124 | } 125 | } 126 | 127 | class CacheObserver extends Subscriber { 128 | 129 | ObservableWrapper observableWrapper; 130 | Subscriber subscriber; 131 | Action1 storeCacheAction; 132 | 133 | public CacheObserver(ObservableWrapper observableWrapper, Subscriber subscriber, Action1 storeCacheAction) { 134 | this.observableWrapper = observableWrapper; 135 | this.subscriber = subscriber; 136 | this.storeCacheAction = storeCacheAction; 137 | } 138 | 139 | @Override 140 | public void onCompleted() { 141 | if (debug) Log.i(TAG, "cache onCompleted"); 142 | cacheLatch.countDown(); 143 | } 144 | 145 | @Override 146 | public void onError(Throwable e) { 147 | if (debug) Log.e(TAG, "cache onError"); 148 | Log.e(TAG, "read cache error:" + e.getMessage()); 149 | if (debug) e.printStackTrace(); 150 | cacheLatch.countDown(); 151 | } 152 | 153 | @Override 154 | public void onNext(T o) { 155 | if (debug) Log.i(TAG, "cache onNext o:" + o); 156 | observableWrapper.setData(o); 157 | logThread(""); 158 | if (netLatch.getCount() > 0) { 159 | if (debug) Log.e(TAG, " check subscriber :" + subscriber + " isUnsubscribed:" + subscriber.isUnsubscribed()); 160 | if (subscriber != null && !subscriber.isUnsubscribed()) { 161 | subscriber.onNext(o);// FIXME: issue A:外面如果ObservableOn 其他线程,将会是异步操作,如果在实际的onNext调用之前,发生了onComplete或者onError,将会unsubscribe,导致onNext没有被调用 162 | } 163 | } else { 164 | if (debug) Log.e(TAG, "net result had been load,so cache is not need to load"); 165 | } 166 | } 167 | } 168 | 169 | public void logThread(String tag) { 170 | if (debug) Log.i(TAG, tag + " : " + Thread.currentThread().getName()); 171 | } 172 | 173 | } 174 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/BasicCache.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | import android.util.LruCache; 6 | 7 | import com.jakewharton.disklrucache.DiskLruCache; 8 | 9 | import java.io.File; 10 | import java.io.IOException; 11 | import java.nio.charset.Charset; 12 | 13 | import okhttp3.HttpUrl; 14 | import okhttp3.Request; 15 | import okhttp3.ResponseBody; 16 | import okio.Buffer; 17 | 18 | /** 19 | * A basic caching system that stores responses in RAM and disk 20 | * It uses {@link DiskLruCache} and {@link LruCache} to do the former. 21 | */ 22 | public class BasicCache implements IRxCache { 23 | private DiskLruCache diskCache; 24 | private LruCache memoryCache; 25 | 26 | public BasicCache(File diskDirectory, long maxDiskSize, int memoryEntries) { 27 | try { 28 | diskCache = DiskLruCache.open(diskDirectory, 1, 1, maxDiskSize); 29 | } catch (IOException exc) { 30 | Log.e("BasicCache", "", exc); 31 | diskCache = null; 32 | } 33 | 34 | memoryCache = new LruCache<>(memoryEntries); 35 | } 36 | 37 | private static final long REASONABLE_DISK_SIZE = 1024 * 1024; // 1 MB 38 | private static final int REASONABLE_MEM_ENTRIES = 50; // 50 entries 39 | 40 | /*** 41 | * Constructs a BasicCaching system using settings that should work for everyone 42 | * 43 | * @param context 上下文 44 | * @return BasicCache 45 | */ 46 | public static BasicCache fromCtx(Context context) { 47 | return new BasicCache( 48 | new File(context.getCacheDir(), "retrofit_rxcache"), 49 | REASONABLE_DISK_SIZE, 50 | REASONABLE_MEM_ENTRIES); 51 | } 52 | 53 | private String urlToKey(HttpUrl url) { 54 | return MD5.getMD5(url.toString()); 55 | } 56 | 57 | @Override 58 | public void addInCache(Request request, Buffer buffer) { 59 | byte[] rawResponse = buffer.readByteArray(); 60 | String cacheKey = urlToKey(request.url()); 61 | memoryCache.put(cacheKey, rawResponse); 62 | 63 | try { 64 | DiskLruCache.Editor editor = diskCache.edit(urlToKey(request.url())); 65 | editor.set(0, new String(rawResponse, Charset.defaultCharset())); 66 | editor.commit(); 67 | } catch (IOException exc) { 68 | Log.e("BasicCache", "", exc); 69 | } 70 | } 71 | 72 | /** 73 | * @param request 74 | * @return 75 | */ 76 | @Override 77 | public ResponseBody getFromCache(Request request) { 78 | String cacheKey = urlToKey(request.url()); 79 | byte[] memoryResponse = (byte[]) memoryCache.get(cacheKey); 80 | if (memoryResponse != null) { 81 | Log.d("BasicCache", "Memory hit!"); 82 | return ResponseBody.create(null, memoryResponse); 83 | } 84 | 85 | try { 86 | DiskLruCache.Snapshot cacheSnapshot = diskCache.get(cacheKey); 87 | if (cacheSnapshot != null) { 88 | Log.d("BasicCache", "Disk hit!"); 89 | return ResponseBody.create(null, cacheSnapshot.getString(0).getBytes()); 90 | } else { 91 | return null; 92 | } 93 | } catch (IOException exc) { 94 | return null; 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/CacheNetOnSubscribeFactory.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | import rx.Observable; 4 | import rx.functions.Action1; 5 | 6 | /** 7 | * User: cpoopc 8 | * Date: 2016-05-15 9 | * Time: 11:36 10 | * Ver.: 0.1 11 | */ 12 | public class CacheNetOnSubscribeFactory { 13 | 14 | private boolean syncMode; 15 | 16 | public CacheNetOnSubscribeFactory() { 17 | this.syncMode = true; 18 | } 19 | 20 | public CacheNetOnSubscribeFactory(boolean syncMode) { 21 | this.syncMode = syncMode; 22 | } 23 | 24 | public Observable.OnSubscribe create(Observable cacheObservable, Observable netObservable, Action1 storeCacheAction) { 25 | if (syncMode) { 26 | return new SyncOnSubscribeCacheNet<>(cacheObservable, netObservable, storeCacheAction); 27 | } else { 28 | return new AsyncOnSubscribeCacheNet<>(cacheObservable, netObservable, storeCacheAction); 29 | } 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/IRxCache.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | 4 | import okhttp3.Request; 5 | import okhttp3.ResponseBody; 6 | import okio.Buffer; 7 | 8 | /** 9 | * User: cpoopc 10 | * Date: 2016-01-18 11 | * Time: 10:19 12 | * Ver.: 0.1 13 | */ 14 | public interface IRxCache { 15 | 16 | void addInCache(Request request, Buffer buffer); 17 | ResponseBody getFromCache(Request request); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/MD5.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | 4 | import java.security.MessageDigest; 5 | import java.security.NoSuchAlgorithmException; 6 | 7 | /** 8 | * 提供MD5加密方法 9 | *

10 | * Description:描述 11 | *

12 | */ 13 | public class MD5 { 14 | 15 | private static final String TAG = "MD5"; 16 | 17 | /** 18 | * 对输入文本进行MD5加密 19 | * @param info 被加密文本,如果输入为null则返回null 20 | * @return MD5 加密后的内容,如果为null说明输入为null 21 | */ 22 | public static String getMD5(String info) { 23 | return getMD5(info.getBytes()); 24 | } 25 | 26 | /** 27 | * 对输入文本进行MD5加密 28 | * @param info 被加密文本 如果输入为null则返回null 29 | * @return MD5加密后的内容,如果为null说明输入为null 30 | */ 31 | public static String getMD5(byte[] info) { 32 | if (null == info || info.equals("")) { 33 | return null; 34 | } 35 | StringBuffer buf = new StringBuffer(""); 36 | MessageDigest md; 37 | try { 38 | md = MessageDigest.getInstance("MD5"); 39 | } catch (NoSuchAlgorithmException e) { 40 | e.printStackTrace(); 41 | return null; 42 | } 43 | md.update(info); 44 | byte b[] = md.digest(); 45 | int i; 46 | 47 | for (int offset = 0; offset < b.length; offset++) { 48 | i = b[offset]; 49 | if (i < 0) 50 | i += 256; 51 | if (i < 16) 52 | buf.append("0"); 53 | buf.append(Integer.toHexString(i)); 54 | } 55 | return buf.toString(); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/OnSubscribeCacheNet.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | 4 | import java.util.concurrent.CountDownLatch; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | import android.util.Log; 8 | import rx.Observable; 9 | import rx.Subscriber; 10 | import rx.Subscription; 11 | import rx.functions.Action1; 12 | import rx.schedulers.Schedulers; 13 | 14 | /** 15 | * 缓存+网络请求 16 | * User: cpoopc 17 | * Date: 2016-01-18 18 | * Time: 10:19 19 | * Ver.: 0.1 20 | */ 21 | public class OnSubscribeCacheNet implements Observable.OnSubscribe { 22 | 23 | private final boolean debug = false; 24 | private final String TAG = "OnSubscribeCacheNet:"; 25 | 26 | // 读取缓存 27 | private ObservableWrapper cacheObservable; 28 | 29 | // 读取网络 30 | private ObservableWrapper netObservable; 31 | 32 | // 网络读取完毕,缓存动作 33 | private Action1 storeCacheAction; 34 | 35 | private int stepIndex; 36 | private final int finalStepIndex; 37 | private AtomicInteger overCount = new AtomicInteger(0); 38 | private boolean sync = true;// true 同步,false:异步 39 | private CountDownLatch cacheLatch = new CountDownLatch(1); 40 | 41 | public OnSubscribeCacheNet(Observable cacheObservable, Observable netObservable, Action1 storeCacheAction) { 42 | if (cacheObservable != null) { 43 | this.cacheObservable = new ObservableWrapper(1, cacheObservable); 44 | } 45 | this.netObservable = new ObservableWrapper(2, netObservable); 46 | this.storeCacheAction = storeCacheAction; 47 | finalStepIndex = 2; 48 | } 49 | 50 | @Override 51 | public void call(Subscriber subscriber) { 52 | if (cacheObservable != null) { 53 | if (sync) { 54 | cacheObservable.getObservable().unsafeSubscribe(new CacheNetObserver(cacheObservable, subscriber, storeCacheAction)); 55 | } else { 56 | cacheObservable.getObservable().subscribeOn(Schedulers.io()).unsafeSubscribe(new CacheNetObserver(cacheObservable, subscriber, storeCacheAction)); 57 | } 58 | } 59 | if (sync) { 60 | netObservable.getObservable().unsafeSubscribe(new CacheNetObserver(netObservable, subscriber, storeCacheAction)); 61 | } else { 62 | netObservable.getObservable().subscribeOn(Schedulers.newThread()).unsafeSubscribe(new CacheNetObserver(netObservable, subscriber, storeCacheAction)); 63 | } 64 | } 65 | 66 | class ObservableWrapper { 67 | 68 | int index; 69 | Observable observable; 70 | T data; 71 | 72 | public ObservableWrapper(int index, Observable observable) { 73 | this.index = index; 74 | this.observable = observable; 75 | } 76 | 77 | public int getIndex() { 78 | return index; 79 | } 80 | 81 | public Observable getObservable() { 82 | return observable; 83 | } 84 | 85 | public T getData() { 86 | return data; 87 | } 88 | 89 | public void setData(T data) { 90 | this.data = data; 91 | } 92 | } 93 | 94 | class CacheNetObserver extends Subscriber { 95 | 96 | ObservableWrapper observableWrapper; 97 | Subscriber subscriber; 98 | Action1 storeCacheAction; 99 | 100 | public CacheNetObserver(ObservableWrapper observableWrapper, Subscriber subscriber, Action1 storeCacheAction) { 101 | this.observableWrapper = observableWrapper; 102 | this.subscriber = subscriber; 103 | this.storeCacheAction = storeCacheAction; 104 | } 105 | 106 | @Override 107 | public void onCompleted() { 108 | if (finalStepIndex == observableWrapper.getIndex()) { 109 | if(debug) Log.i(TAG,"onCompleted stepIndex:" + observableWrapper.getIndex()); 110 | try { 111 | if (storeCacheAction != null) { 112 | storeCacheAction.call(observableWrapper.getData()); 113 | } 114 | } catch (Exception e) { 115 | onError(e); 116 | } 117 | overCount.addAndGet(1); 118 | if (subscriber != null && !subscriber.isUnsubscribed()) { 119 | subscriber.onCompleted(); 120 | } 121 | } else { 122 | if(debug) Log.i(TAG,"onCompleted stepIndex:" + observableWrapper.getIndex() + " still not completed"); 123 | overCount.addAndGet(1); 124 | } 125 | 126 | } 127 | 128 | @Override 129 | public void onError(Throwable e) { 130 | if(debug) Log.e(TAG, "onError stepIndex:" + observableWrapper.getIndex()); 131 | overCount.addAndGet(1); 132 | if (finalStepIndex == observableWrapper.getIndex()) { 133 | while (overCount.get() < finalStepIndex) { 134 | if(debug) Log.e(TAG,"onError stepIndex:" + observableWrapper.getIndex() + " overCount.get() < finalStepIndex"); 135 | try { 136 | Thread.sleep(500); 137 | } catch (InterruptedException e1) { 138 | e1.printStackTrace(); 139 | } 140 | } 141 | if (!sync) { 142 | try { 143 | cacheLatch.await(); 144 | } catch (InterruptedException e1) { 145 | e1.printStackTrace(); 146 | } 147 | // try {// FIXME: 2016/1/18 issue A 临时解决办法 148 | // Thread.sleep(500); 149 | // } catch (InterruptedException e1) { 150 | // e1.printStackTrace(); 151 | // } 152 | } 153 | if (subscriber != null && !subscriber.isUnsubscribed()) { 154 | subscriber.onError(e); 155 | } 156 | } 157 | } 158 | 159 | @Override 160 | public void onNext(T o) { 161 | if(debug) Log.i(TAG,"stepIndex :" + stepIndex + " observableWrapper.getIndex():" + observableWrapper.getIndex() + " o:"+o); 162 | observableWrapper.setData(o); 163 | if (stepIndex < observableWrapper.getIndex()) { 164 | stepIndex = observableWrapper.getIndex(); 165 | if(debug) Log.i(TAG,"stepIndex :" + stepIndex + " observableWrapper.getIndex():" + observableWrapper.getIndex()); 166 | logThread(""); 167 | if(debug) Log.e(TAG, " check subscriber :" + subscriber + " isUnsubscribed:" + subscriber.isUnsubscribed()); 168 | if (subscriber != null && !subscriber.isUnsubscribed()) { 169 | subscriber.onNext(o);// FIXME: issue A:外面如果ObservableOn 其他线程,将会是异步操作,如果在实际的onNext调用之前,发生了onComplete或者onError,将会unsubscribe,导致onNext没有被调用 170 | } 171 | } 172 | } 173 | } 174 | 175 | public void logThread(String tag) { 176 | if(debug) Log.i(TAG, tag + " : " + Thread.currentThread().getName()); 177 | } 178 | 179 | } 180 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/RxCacheCallAdapterFactory.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | import java.io.IOException; 4 | import java.lang.annotation.Annotation; 5 | import java.lang.reflect.Array; 6 | import java.lang.reflect.Field; 7 | import java.lang.reflect.GenericArrayType; 8 | import java.lang.reflect.InvocationTargetException; 9 | import java.lang.reflect.Method; 10 | import java.lang.reflect.ParameterizedType; 11 | import java.lang.reflect.Type; 12 | import java.lang.reflect.TypeVariable; 13 | import java.lang.reflect.WildcardType; 14 | 15 | import okhttp3.Request; 16 | import okhttp3.RequestBody; 17 | import okhttp3.ResponseBody; 18 | import okio.Buffer; 19 | import retrofit2.Call; 20 | import retrofit2.CallAdapter; 21 | import retrofit2.Converter; 22 | import retrofit2.Response; 23 | import retrofit2.Retrofit; 24 | import rx.Observable; 25 | import rx.Subscriber; 26 | import rx.exceptions.Exceptions; 27 | import rx.functions.Action0; 28 | import rx.functions.Action1; 29 | import rx.functions.Func1; 30 | import rx.subscriptions.Subscriptions; 31 | 32 | /** 33 | * User: cpoopc 34 | * Date: 2016/1/16 35 | * Time: 20:33 36 | */ 37 | public class RxCacheCallAdapterFactory extends CallAdapter.Factory { 38 | private final IRxCache cachingSystem; 39 | private final CacheNetOnSubscribeFactory cacheNetOnSubscribeFactory; 40 | 41 | public RxCacheCallAdapterFactory(IRxCache cachingSystem) { 42 | this.cachingSystem = cachingSystem; 43 | this.cacheNetOnSubscribeFactory = new CacheNetOnSubscribeFactory(); 44 | } 45 | 46 | public RxCacheCallAdapterFactory(IRxCache cachingSystem, boolean sync) { 47 | this.cachingSystem = cachingSystem; 48 | this.cacheNetOnSubscribeFactory = new CacheNetOnSubscribeFactory(sync); 49 | } 50 | 51 | public static RxCacheCallAdapterFactory create(IRxCache cachingSystem) { 52 | return new RxCacheCallAdapterFactory(cachingSystem); 53 | } 54 | 55 | public static RxCacheCallAdapterFactory create(IRxCache cachingSystem, boolean sync) { 56 | return new RxCacheCallAdapterFactory(cachingSystem, sync); 57 | } 58 | 59 | @Override 60 | public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) { 61 | Class rawType = getRawType(returnType); 62 | if (rawType != Observable.class) { 63 | return null; 64 | } 65 | if (!(returnType instanceof ParameterizedType)) { 66 | String name = "Observable"; 67 | throw new IllegalStateException(name + " return type must be parameterized" 68 | + " as " + name + " or " + name + ""); 69 | } 70 | 71 | Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType); 72 | Class genRawType = getRawType(observableType); 73 | if (genRawType == RxCacheResult.class) { 74 | Type actualType = ((ParameterizedType) observableType).getActualTypeArguments()[0]; 75 | android.util.Log.d("cp:RxCache", "RxCacheResult T:" + actualType); 76 | // TODO: 2016/2/28 添加Response类支持 77 | return new RxCacheCallAdapter(actualType, annotations, retrofit, cachingSystem); 78 | } 79 | return null; 80 | } 81 | 82 | public static T getFromCache(Request request, Converter converter, IRxCache cachingSystem) { 83 | try { 84 | return converter.convert(cachingSystem.getFromCache(request)); 85 | } catch (IOException e) { 86 | e.printStackTrace(); 87 | } 88 | return null; 89 | } 90 | 91 | public static void addToCache(Request request, T data, Converter converter, IRxCache cachingSystem) { 92 | try { 93 | Buffer buffer = new Buffer(); 94 | RequestBody requestBody = converter.convert(data); 95 | requestBody.writeTo(buffer); 96 | cachingSystem.addInCache(request, buffer); 97 | } catch (IOException e) { 98 | e.printStackTrace(); 99 | } 100 | } 101 | 102 | /** 103 | * 将Call转换成带有缓存功能的Observable 104 | */ 105 | final class RxCacheCallAdapter implements CallAdapter { 106 | private final Type responseType; 107 | private final Annotation[] annotations; 108 | private final Retrofit retrofit; 109 | private final IRxCache cachingSystem; 110 | 111 | public RxCacheCallAdapter(Type responseType, Annotation[] annotations, Retrofit retrofit, 112 | IRxCache cachingSystem) { 113 | this.responseType = responseType; 114 | this.annotations = annotations; 115 | this.retrofit = retrofit; 116 | this.cachingSystem = cachingSystem; 117 | } 118 | 119 | 120 | /*** 121 | * Inspects an OkHttp-powered Call and builds a Request 122 | * * @return A valid Request (that contains query parameters, right method and endpoint) 123 | */ 124 | private Request buildRequestFromCall(Call call) { 125 | Request request = null; 126 | try { 127 | // 增加了call.request()方法:https://github.com/square/retrofit/commit/b3ea768567e9e1fb1ba987bea021dbc0ead4acd4 128 | request = call.request(); 129 | }catch (NoSuchMethodError e) { 130 | try { 131 | // 旧版本需要通过反射获取Request 132 | Field argsField = call.getClass().getDeclaredField("args"); 133 | argsField.setAccessible(true); 134 | Object[] args = (Object[]) argsField.get(call); 135 | 136 | Field requestFactoryField = call.getClass().getDeclaredField("requestFactory"); 137 | requestFactoryField.setAccessible(true); 138 | Object requestFactory = requestFactoryField.get(call); 139 | Method createMethod = requestFactory.getClass().getDeclaredMethod("create", Object[].class); 140 | createMethod.setAccessible(true); 141 | request = (Request) createMethod.invoke(requestFactory, new Object[]{args}); 142 | } catch (Exception exc) { 143 | return null; 144 | } 145 | } 146 | return request; 147 | } 148 | 149 | @Override 150 | public Type responseType() { 151 | return responseType; 152 | } 153 | 154 | @Override 155 | public Observable> adapt(Call call) { 156 | final Request request = buildRequestFromCall(call); 157 | Observable> mCacheResultObservable = Observable.create(new Observable.OnSubscribe>() { 158 | @Override 159 | public void call(Subscriber> subscriber) { 160 | // read cache 161 | Converter responseConverter = getResponseConverter(retrofit, responseType, annotations); 162 | RESULT serverResult = getFromCache(request, responseConverter, cachingSystem); 163 | if (subscriber.isUnsubscribed()) return; 164 | if (serverResult != null) { 165 | subscriber.onNext(new RxCacheResult(true, serverResult)); 166 | } 167 | subscriber.onCompleted(); 168 | } 169 | }); 170 | Action1> mCacheAction = new Action1>() { 171 | @Override 172 | public void call(RxCacheResult serverResult) { 173 | // store cache action 174 | if (serverResult != null) { 175 | RESULT resultModel = serverResult.getResultModel(); 176 | Converter requestConverter = getRequestConverter(retrofit, responseType, annotations); 177 | addToCache(request, resultModel, requestConverter, cachingSystem); 178 | } 179 | } 180 | }; 181 | 182 | Observable> serverObservable = Observable.create(new CallOnSubscribe<>(call)) // 183 | .flatMap(new Func1, Observable>>() { 184 | @Override 185 | public Observable> call(Response response) { 186 | boolean success = false; 187 | try { 188 | success = response.isSuccessful(); 189 | }catch (NoSuchMethodError e2) { 190 | try { 191 | Method isSuccess = response.getClass().getDeclaredMethod("isSuccess"); 192 | success = (boolean) isSuccess.invoke(response); 193 | } catch (NoSuchMethodException e) { 194 | e.printStackTrace(); 195 | } catch (InvocationTargetException e) { 196 | e.printStackTrace(); 197 | } catch (IllegalAccessException e) { 198 | e.printStackTrace(); 199 | } 200 | } 201 | if (success) { 202 | return Observable.just(new RxCacheResult(false, response.body())); 203 | } 204 | return Observable.error(new RxCacheHttpException(response)); 205 | } 206 | }); 207 | return Observable.create(cacheNetOnSubscribeFactory.create(mCacheResultObservable, serverObservable, mCacheAction)); 208 | } 209 | 210 | } 211 | 212 | final class CallOnSubscribe implements Observable.OnSubscribe> { 213 | private final Call originalCall; 214 | 215 | private CallOnSubscribe(Call originalCall) { 216 | this.originalCall = originalCall; 217 | } 218 | 219 | @Override 220 | public void call(final Subscriber> subscriber) { 221 | // Since Call is a one-shot type, clone it for each new subscriber. 222 | final Call call = originalCall.clone(); 223 | 224 | // Attempt to cancel the call if it is still in-flight on unsubscription. 225 | subscriber.add(Subscriptions.create(new Action0() { 226 | @Override 227 | public void call() { 228 | call.cancel(); 229 | } 230 | })); 231 | 232 | if (subscriber.isUnsubscribed()) { 233 | return; 234 | } 235 | 236 | try { 237 | Response response = call.execute(); 238 | if (!subscriber.isUnsubscribed()) { 239 | subscriber.onNext(response); 240 | } 241 | } catch (Throwable t) { 242 | Exceptions.throwIfFatal(t); 243 | if (!subscriber.isUnsubscribed()) { 244 | subscriber.onError(t); 245 | } 246 | return; 247 | } 248 | 249 | if (!subscriber.isUnsubscribed()) { 250 | subscriber.onCompleted(); 251 | } 252 | } 253 | } 254 | 255 | @SuppressWarnings("unchecked") 256 | public static Converter getResponseConverter(Retrofit retrofit, Type dataType, Annotation[] annotations) { 257 | return retrofit.responseBodyConverter(dataType, annotations); 258 | } 259 | 260 | @SuppressWarnings("unchecked") 261 | public static Converter getRequestConverter(Retrofit retrofit, Type dataType, Annotation[] annotations) { 262 | // TODO gson beta4版本中paramsAnnotations与获取converter没有什么关系 263 | // 此处获取RequestBodyConverter,是为了将model转成Buffer,以便写入cache 264 | return retrofit.requestBodyConverter(dataType, new Annotation[0], annotations); 265 | } 266 | 267 | // This method is copyright 2008 Google Inc. and is taken from Gson under the Apache 2.0 license. 268 | public static Class getRawType(Type type) { 269 | if (type instanceof Class) { 270 | // Type is a normal class. 271 | return (Class) type; 272 | 273 | } else if (type instanceof ParameterizedType) { 274 | ParameterizedType parameterizedType = (ParameterizedType) type; 275 | 276 | // I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but 277 | // suspects some pathological case related to nested classes exists. 278 | Type rawType = parameterizedType.getRawType(); 279 | if (!(rawType instanceof Class)) throw new IllegalArgumentException(); 280 | return (Class) rawType; 281 | 282 | } else if (type instanceof GenericArrayType) { 283 | Type componentType = ((GenericArrayType) type).getGenericComponentType(); 284 | return Array.newInstance(getRawType(componentType), 0).getClass(); 285 | 286 | } else if (type instanceof TypeVariable) { 287 | // We could use the variable's bounds, but that won't work if there are multiple. Having a raw 288 | // type that's more general than necessary is okay. 289 | return Object.class; 290 | 291 | } else if (type instanceof WildcardType) { 292 | return getRawType(((WildcardType) type).getUpperBounds()[0]); 293 | 294 | } else { 295 | String className = type == null ? "null" : type.getClass().getName(); 296 | throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " 297 | + "GenericArrayType, but <" + type + "> is of type " + className); 298 | } 299 | } 300 | 301 | } 302 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/RxCacheHttpException.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | import retrofit2.Response; 4 | 5 | /** Exception for an unexpected, non-2xx HTTP response. */ 6 | public final class RxCacheHttpException extends Exception { 7 | private final int code; 8 | private final String message; 9 | private final transient Response response; 10 | 11 | public RxCacheHttpException(Response response) { 12 | super("HTTP " + response.code() + " " + response.message()); 13 | this.code = response.code(); 14 | this.message = response.message(); 15 | this.response = response; 16 | } 17 | 18 | /** HTTP status code. */ 19 | public int code() { 20 | return code; 21 | } 22 | 23 | /** HTTP status message. */ 24 | public String message() { 25 | return message; 26 | } 27 | 28 | /** 29 | * The full HTTP response. This may be null if the exception was serialized. 30 | */ 31 | public Response response() { 32 | return response; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/RxCacheResult.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | /** 4 | * User: cpoopc 5 | * Date: 2016/2/28 6 | * Time: 21:14 7 | */ 8 | public class RxCacheResult { 9 | private boolean isCache; 10 | private T resultModel; 11 | 12 | public RxCacheResult(boolean isCache, T resultModel) { 13 | this.isCache = isCache; 14 | this.resultModel = resultModel; 15 | } 16 | 17 | public boolean isCache() { 18 | return isCache; 19 | } 20 | 21 | public void setCache(boolean cache) { 22 | isCache = cache; 23 | } 24 | 25 | public T getResultModel() { 26 | return resultModel; 27 | } 28 | 29 | public void setResultModel(T resultModel) { 30 | this.resultModel = resultModel; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/java/com/cpoopc/retrofitrxcache/SyncOnSubscribeCacheNet.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | import rx.Observable; 4 | import rx.Subscriber; 5 | import rx.functions.Action1; 6 | 7 | /** 8 | * User: cpoopc 9 | * Date: 2016/05/15 10 | * Time: 12:58 11 | */ 12 | public class SyncOnSubscribeCacheNet extends AsyncOnSubscribeCacheNet { 13 | public SyncOnSubscribeCacheNet(Observable cacheObservable, Observable netObservable, Action1 storeCacheAction) { 14 | super(cacheObservable, netObservable, storeCacheAction); 15 | } 16 | 17 | @Override 18 | public void call(Subscriber subscriber) { 19 | cacheObservable.getObservable().unsafeSubscribe(new CacheObserver(cacheObservable, subscriber, storeCacheAction)); 20 | netObservable.getObservable().unsafeSubscribe(new NetObserver(netObservable, subscriber, storeCacheAction)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | RetrofitRxCache 3 | 4 | -------------------------------------------------------------------------------- /retrofit-rxcache/src/test/java/com/cpoopc/retrofitrxcache/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.cpoopc.retrofitrxcache; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':retrofit-rxcache' 2 | --------------------------------------------------------------------------------