1.Rxjava的介绍
根据github官方介绍“a library for composing asynchronous and event-based programs using observable sequences for the Java VM“,我来翻译哈,Rxjava是一个在java虚拟机上使用可观测的序列实现异步和基于事件驱动的库,说到底,Rxjava就是应用于java语言中的一个实现异步且基于事件驱动的工具库,这下概念搞明白了,不晓得你搞明白没,反正我是明白了。
2.Rxjava的原理
Rxjava是一种扩展式的观察者模式,但与最初的观察者模式又有些差异。那么,到底怎么回事呢?莫急,听我慢慢分解:
通俗点讲,Rxjava这种扩展式的观察者模式,需要被观察者(Observable)在状态改变的时候通知观察者(Observer),继而观察者引发一系列的动作。这种模式听起来很奇怪,就像警察抓小偷一样,在小偷实行偷取东西,小偷必须通知警察,然后警察才能实行抓捕行动,貌似警察方显格外的被动了,不过没办法,这就是我们要学习的Rxjava的原理。
Observable-------subscribe-----------》observer
3.Rxjava重点解析
1.Observer的创建
//创建观察者2.Observable的创建
final Observer<String> myObserver = new Observer<String>() {
@Override
public void onCompleted() {
System.out.println("completed");
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(String s) {
System.out.println(s);
}
};
//创建被观察者3.实现两者的订阅(绑定)
Observable<String> myObservable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
myObserver.onNext("hello");
myObserver.onNext("world");
myObserver.onNext("zhangxing");
myObserver.onCompleted();
}
});
//实现订阅关系
myObservable.subscribe(myObserver);
4.Rxjava重要operators的解析
1.just:将传入的参数依次发送出来
Observable.just("zhangxing","helloworld")2.from ( T[ ] ):将传入的数组或Iterable拆分成具体对象后传出来
等同于://onNext("zhangixng");
//onNext("helloworld");
//onCompleted();
String[] words = {"Hello", "Hi", "Aloha"};3.map:可以传出一个新的数据类型的Observable对象
Observable observable = Observable.from(words);
等同于 // 将会依次调用:
// onNext("Hello");
// onNext("Hi");
// onNext("Aloha");
// onCompleted();
Observable.just("zhangxing","helloworld")4.flatMap:接收一个Observable输出作为入参,同时输出另一个Observable对象
.map(new Func1<String,Integer>() {
@Override
public Integer call(String s) {
return s.hashCode();
}
})
没用flatMap之前:
Observable.from(words)用了flatMap之后
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Observable.from(wordss)
.subscribe(new Action1<String>() {
@Override
public void call(String word) {
newsTv.setText(word);
}
});
}
});
final String[] wordss = new String[]{"hello","zhangixng"};是不是代码简洁了很多,哈哈,这就是它的强大之处,这个操作符也是Rxjava的重中之重,虽然理解起来有点难度,但是一旦理解,后果不堪设想,哈哈!
Observable.from(words)
.flatMap(new Func1<List<String>, Observable<String>>() {
@Override
public Observable<String> call(List<String> word) {
return Observable.from(word) ;
}
);
5.filter:过滤一些不满足条件的结果
query("Hello, world!")6.take:输出最多指定数量的结果
.flatMap(urls -> Observable.from(urls))
.flatMap(url -> getTitle(url))
.filter(title -> title != null)
.take(5)
.doOnNext(title -> saveTitle(title))
.subscribe(title -> System.out.println(title));
上段代码也演示了take的功能,这里就不赘述了。
7.doOnNext():在输出一个元素之前做一些额外的事情。
在第5段代码中,允许我们在每次输出一个元素之前做一些额外的事情,比如这里的保存标题
5.Retrofit与Rxjava的完美结合
1.build.gradle中添加配置:
compile 'com.squareup.retrofit2:retrofit:2.1.0'2.申明接口类:
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'io.reactivex:rxjava:1.1.0'
public interface APIService {这时的TopNew的修饰符就是Observable了,注意了不再是Call了哦!!
@GET("index")
Observable<TopNews> getNews(@Query("type") String type, @Query("key")String key);
}
3.javaBean的生成(我这里采用聚合数据的头条新闻的接口)
public class TopNews implements Serializable {4,.请求代码的实现:
private String reason;
private ResultBean result;
private int error_code;
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public static class ResultBean {
private String stat;
/**
* title : 多么痛的领悟!河南一对情侣同居生子没领证 男方几年后另觅新欢
* date : 2016-10-16 17:37
* category : 社会
* author_name : 台海网
* thumbnail_pic_s : http://02.imgmini.eastday.com/mobile/20161016/20161016173718_d2ea108abd6ed284b35e0e6c7327635f_1_mwpm_03200403.jpeg
* url : http://mini.eastday.com/mobile/161016173718330.html?qid=juheshuju
* thumbnail_pic_s03 : http://02.imgmini.eastday.com/mobile/20161016/20161016173718_d2ea108abd6ed284b35e0e6c7327635f_1_mwpl_05500201.jpeg
*/
private List<DataBean> data;
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String title;
private String date;
private String category;
private String author_name;
private String thumbnail_pic_s;
private String url;
private String thumbnail_pic_s03;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAuthor_name() {
return author_name;
}
public void setAuthor_name(String author_name) {
this.author_name = author_name;
}
public String getThumbnail_pic_s() {
return thumbnail_pic_s;
}
public void setThumbnail_pic_s(String thumbnail_pic_s) {
this.thumbnail_pic_s = thumbnail_pic_s;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnail_pic_s03() {
return thumbnail_pic_s03;
}
public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
this.thumbnail_pic_s03 = thumbnail_pic_s03;
}
}
}
}
public void captureNews(View view){效果图:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://v.juhe.cn/toutiao/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
service.getNews("shehui","2be4390ab0c91110e4cde2edfddad05d")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<TopNews>() {
@Override
public void onCompleted() {
Toast.makeText(MainActivity.this, "Get Top News Completed", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(TopNews topNews) {
newsTv.setText(topNews.getResult().getData().get(1).getTitle());
}
});
}
好了,请求成功了,今天就到这里了,大家有什么问题的话,私信我,我是张星,欢迎关注!!