Rx出来很久了,long long ago 就学习了一下,但只是初步的了解过一些,并没怎么实战过,现在都忘的差不多了,现在公司差不多都要用RxJava RxAndroid相关开发,特此重新理解学习一下这方面的知识,写点blog做个记录和分享。
首先,Rx相关的知识最好通过github上面去获取,以免其他渠道获取的信息言辞不达意亦或者错误的理解,先下载RxJava源码到本地浏览个大概即可,脑海留着些许印象,不至于后面开发感觉代码有点抽象。
项目添加RxJava依赖
compile 'io.reactivex:rxjava:1.0.14'
Observable和OnSubscribe是Rx最常见的两个类,我是这样理解的:Observable就是大明星,OnSubscribe是粉丝,明星blog发布,关注他的粉丝就能进行评论阅读等作出各自的反应,如果粉丝取消了关注就不会再接受到明星发布的blog的消息通知。现在先来梳理一下脉络,这两个类的内部具体实现暂且不看。
public interface Observer<T> {
/** * Notifies the Observer that the {@link Observable} has finished sending push-based notifications. * <p> * The {@link Observable} will not call this method if it calls {@link #onError}. */
void onCompleted();
/** * Notifies the Observer that the {@link Observable} has experienced an error condition. * <p> * If the {@link Observable} calls this method, it will not thereafter call {@link #onNext} or * {@link #onCompleted}. * * @param e * the exception encountered by the Observable */
void onError(Throwable e);
/** * Provides the Observer with a new item to observe. * <p> * The {@link Observable} may call this method 0 or more times. * <p> * The {@code Observable} will not call this method again after it calls either {@link #onCompleted} or * {@link #onError}. * * @param t * the item emitted by the Observable */
void onNext(T t);
}
onError方法和onCompleted方法不会同时存在,互斥关系,程序不管是哪里一旦出错立即onError方法回调,不会再继续执行,整个流程执行完成没出错call里手动调用onCompleted。onNext稍后再提,下面再看Subscription
public interface Subscription {
/** * Stops the receipt of notifications on the {@link Subscriber} that was registered when this Subscription * was received. * <p> * This allows unregistering an {@link Subscriber} before it has finished receiving all events (i.e. before * onCompleted is called). */
void unsubscribe();
/** * Indicates whether this {@code Subscription} is currently unsubscribed. * * @return {@code true} if this {@code Subscription} is currently unsubscribed, {@code false} otherwise */
boolean isUnsubscribed();
}
isUnsubscribed用于判断订阅者有没有取消订阅,unsubscribe就是用于取消订阅啦,这些接口定义具体实现在哪里呢,该怎么用呢?且看下面代码块来帮助我们理解
public interface Action1<T> extends Action {
void call(T t);
}
.............
public abstract class Subscriber<T> implements Observer<T>, Subscription {
}
.......................
public class Observable<T> {
/** * Invoked when Observable.subscribe is called. */
public interface OnSubscribe<T> extends Action1<Subscriber<? super T>> {
// cover for generics insanity
}
public final static <T> Observable<T> create(OnSubscribe<T> f) {
return new Observable<T>(hook.onCreate(f));
}
public final Subscription subscribe(Subscriber<? super T> subscriber) {
return Observable.subscribe(subscriber, this);
}
private static <T> Subscription subscribe(Subscriber<? super T> subscriber, Observable<T> observable) {
}
}
这么直观的代码应该能理解了吧,如果还无法理解,下面通过一组实例来帮助我们加深理解吧。观察者发布事件给订阅者,订阅者在call回调方法处理事情,处理完成后会执行onCompleted回调如果这个过程中出现错误立即onError回调。如果处理事件是N个,你可以选择每次处理完成了调用onNext方法通知观察者一下,处理完了所有的在调用onCompleted(如果你在call方法里面不手动调用onCompleted后面认购订阅事件的回调不会执行的。)
public class RxSimple01 {
private RxSimple01(){
}
public static RxSimple01 newInstance(){
return new RxSimple01();
}
String result = null;
public Observable createObservable(){
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
if(!subscriber.isUnsubscribed()){//如果还没取消订阅执行下面操作
for (int i=0; i<5; i++){
int temp = new Random().nextInt(10);
if (temp > 8) {
//if value>8, we make an error
subscriber.onError(new Throwable(temp+";value >8"));
break;
} else {
subscriber.onNext("temp"+temp+".");
}
if(i==4){
subscriber.onCompleted();
}
}
}
}
});
}
public void initTextView(final TextView textView){
createObservable().subscribe(new Subscriber<String>(){
@Override
public void onCompleted() {
textView.setText(result);
}
@Override
public void onError(Throwable e) {
textView.setText(e.getMessage());
}
@Override
public void onNext(String s) {
result+= s;
}
});
}
}
Create是最基本的创建Observable的操作符,如果你只是创建了然并卵!订阅者没有认购,这个creat只是创建了一个实例而已,也仅此而已。我们需要通过观察者调用subscribe完成订阅者的认购,这样才是一个完整的流程,call方法中的onError等相关方法回调如何关联到下面创建的Subscriber实例的呢?且看下例代码块
private static <T> Subscription subscribe(Subscriber<? super T> subscriber, Observable<T> observable) {
// validate and proceed 观察者发布事件被订阅者认购这件事如果订阅者没有,就会抛出异常
if (subscriber == null) {
throw new IllegalArgumentException("observer can not be null");
}
if (observable.onSubscribe == null) {
throw new IllegalStateException("onSubscribe function can not be null.");
/* * the subscribe function can also be overridden but generally that's not the appropriate approach * so I won't mention that in the exception */
}
// new Subscriber so onStart it
subscriber.onStart();
try {
// allow the hook to intercept and/or decorate 有了订阅者才能在这里执行call函数的回调,所以如果没有发生调用subscribe方法,create的函数内实例的OnSubscribe对应的call还有用么,答案显而易见的
hook.onSubscribeStart(observable, observable.onSubscribe).call(subscriber);
return hook.onSubscribeReturn(subscriber);
} catch (Throwable e) {
//........................
try {
//出现了异常会立即终止,回调error函数
subscriber.onError(hook.onSubscribeError(e));
} catch (OnErrorNotImplementedException e2) {
//...............................
//订阅事件发生了异常会取消订阅
return Subscriptions.unsubscribed();
}
}
上面注释相信非常清晰了吧,Rx我认为也就那么回事:观察者和订阅者,发布事件作为链条。好与坏且不论,我也没资格说啥,还是继续理解学习吧,下一篇操作符。
以上理解如有不对欢迎指出
强烈推荐参考资料
http://mushuichuan.com/2015/12/11/rxjava-operator-1/