關(guān)于RxJava在項(xiàng)目中的配置和使用
RxJava的好處茂嗓,簡單概括就是它使代碼更加簡潔餐茵,高效,靈活述吸!
了解RxJava: https://github.com/lzyzsd/Awesome-RxJava
第一篇博客給對(duì)RxJava感興趣的人一些入門的指引忿族,以及為什么要使用RxJava。
RxJavaDemo:https://github.com/cn-ljb/rxjava_for_android
這個(gè)Demo中示例了RxJava在Android中的應(yīng)用蝌矛。
RxJava道批,RxAndroid,Retrofit,再配合Java8的Lambda表達(dá)式,讓你的代碼看起來像在飛一樣入撒。
Retrolambda是一個(gè)Java類庫隆豹,在Java5、6茅逮、7 上實(shí)現(xiàn)Java8的Lambda表達(dá)式的功能璃赡。你可以通過Retrolambda讓使用Lambda表達(dá)式的Java8代碼運(yùn)行在Java7或更低版本上。不過需要Java 8來編譯源碼献雅。
Android Studio中的配置:
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'me.tatarka:gradle-retrolambda:3.2.5'
}
}
apply plugin: 'me.tatarka.retrolambda'
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
//當(dāng)前依賴庫
dependencies {
compile 'io.reactivex:rxjava:1.1.5'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'com.f2prateek.rx.preferences:rx-preferences:1.0.1'
compile 'com.google.code.gson:gson:2.5'
compile 'com.trello:rxlifecycle:0.6.1'
compile 'com.trello:rxlifecycle-components:0.6.1'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
}
介紹使用RxJava需要的一些相關(guān)庫碉考,在上面的連接中更加詳細(xì):
- https://github.com/ReactiveX/RxJava
- https://github.com/ReactiveX/RxAndroid
- https://github.com/JakeWharton/RxBinding
- https://github.com/f2prateek/rx-preferences
- https://github.com/trello/RxLifecycle
- https://github.com/square/retrofit
- https://github.com/pushtorefresh/storio
- https://github.com/square/sqlbrite
- https://github.com/tbruyelle/RxPermissions
關(guān)于使用RxJava的一些小例子:
// 創(chuàng)建observable
Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("Hello RxJava");
subscriber.onCompleted();
}
});
// 創(chuàng)建subscriber
Subscriber<String> subscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
log(s);
}
};
// 訂閱
observable.subscribe(subscriber);
//上面是基本的用法,我們直接把創(chuàng)建和訂閱連接起來挺身,完整的代碼如下
Observable.just("Hello RxJava").subscribe(new Action1<String>() {
@Override
public void call(String s) {
log(s);
}
});
//使用Lambda表達(dá)式后:
Observable.just("Hello RxJava").subscribe(s -> log(s));
/**
* Android View 事件處理
*/
ViewObservable.clicks(findViewById(R.id.text), false).subscribe(new Action1<OnClickEvent>() {
@Override
public void call(OnClickEvent onClickEvent) {
doSomething();
}
});
使用Lambda表達(dá)式后:
ViewObservable.clicks(findViewById(R.id.text), false).subscribe(s -> doSomething());
網(wǎng)絡(luò)請(qǐng)求方面使用Retrofit2:http://square.github.io/retrofit/
先定義請(qǐng)求接口:
public interface Rservice {
@GET("query?key=12f173de6a551")
Call<WechatBean> getMethod();
@GET("query?key=12f173de6a551")
Observable<WechatBean> getMethodOb();
@POST("user/name")
<T> Observable<WechatBean> postMethodOb(@Body T t);
//下面這種方法是錯(cuò)誤的侯谁,不支持
@GET("{url}")
Call<WechatBean> getMethod(@Path("url") String url);
}
public class Retrofit2Utils {
public static final String BASEURL = "http://apicloud.mob.com/wx/article/category/";
public static void getMethod(Subscriber subscriber){
Rservice rservice = getRetrofit().create(Rservice.class);
rservice.getMethodOb().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.unsubscribeOn(Schedulers.io()).subscribe(subscriber);
}
public static <T> void postMethod(T t,Subscriber subscriber){
Rservice rservice = getRetrofit().create(Rservice.class);
rservice.postMethodOb(t).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.unsubscribeOn(Schedulers.io()).subscribe(subscriber);
}
private static Retrofit getRetrofit(){
return new Retrofit.Builder().baseUrl(BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(genericClient()) //添加統(tǒng)一header
.build();
}
public static OkHttpClient genericClient() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request() .newBuilder()
.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.addHeader("Accept-Encoding", "gzip, deflate")
.addHeader("Connection", "keep-alive")
.addHeader("Accept", "*/*")
.addHeader("Cookie", "add cookies here")
.build();
return chain.proceed(request);
}
}).build();
return httpClient;
}
}
//使用示例:GET請(qǐng)求
Retrofit2Utils.getMethod(new Subscriber<WechatBean>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(WechatBean wechatBean) {
tv_reuslt.setText("Post Result:\r\n" + wechatBean.getMsg());
}
});
//POST請(qǐng)求使用@Body傳一個(gè)對(duì)象
我想抽取一個(gè)公共方法,不在注解里寫url章钾,而是傳url良蒸,@Path注解只支持單個(gè)的字段,不支持如"user/name"帶"/"的字段伍玖,所以只能每個(gè)請(qǐng)求都要寫一個(gè)方法了嫩痰。
另附上一個(gè)不錯(cuò)的Demo:https://github.com/oxoooo/mr-mantou-android