Rxjava (上)

概述:

Rxjava作用:异步,rxjava是实现异步操作的库
Rxjava好处:无论业务逻辑多么复杂,rxjava一样简洁;
Rxjava的异步操作是通过扩展的观察者模式来实现的

Rxjava的观察者模式:

4个角色:
  • Observable :被观察者(主题),决定什么时候出发事件及触发怎样的事件。
  • Observer :观察者,决定事件触发的时候将有怎样的行为
  • Subscriber :订阅
  • Subject :事件

Rxjava的基本实现

Rxjava的基本实现的步骤
  1. 构建build.gradle
  2. 创建Observer观察者
  3. 创建Observable被观察者
  4. subscribe订阅(注册)

步骤的详细说明如下:

第一步:构建build.gradle
    dependencies {
        //...
        compile 'io.reactivex:rxjava:1.2.0'
        compile 'io.reactivex:rxandroid:1.2.1'

    }
第二步:创建Observer观察者

创建方式有如下三种:

  • 创建Observer对象
  • 创建subscriber对象
  • 不完全回调

Observer观察者中主要的回调函数如下:

  • void onCompleted() :通知观察者被观察者已完成发送,如果被观察者调用了onError,则不会调用此方法

  • void onError(Throwable e) :如果Observable调用了此方法,那么就不会调用onNext()方法或onCompleted()

  • void onNext(T t) :Observable可能会0次或多次调用此方法,在Observable调用onCompleted()方法之后不会再调用此方法

  • onStart() :在Subscriber刚开始,事件还未发送之前调用,可用于做一些初始化操作,如数据的清空或重置 ;若准备工作对线程有要求,那么此方法就不合适了,TODO:查看源码看是在哪调用的

其中onCompleted()、 void onError(Throwable e) 、void onNext(T t)是必须要实现的方法。

创建Observer对象代码如下:

Observer observer = new Observer() {
    @Override
    public void onCompleted() {
        
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onNext(String s) {

    }
};

创建subscriber对象代码如下:

Subscriber subscriber = new Subscriber() {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onNext(String s) {

    }
};

不完全回调代码如下:

public class DemoIncompleteCallbackActivity extends Activity {
    private String tag = "DemoIncompleteCallbackActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //不完全回调
        observable1.subscribe(onNextAction);
        observable2.subscribe(onNextAction,onErrorAction);
        observable3.subscribe(onNextAction,onErrorAction,onCompletedAction);
    }

    Observable observable1 = Observable.just(1, 2, 3);
    Observable observable2 = Observable.just(11, 22, 33);
    Observable observable3 = Observable.just(111, 222, 333);

    Action1 onNextAction = new Action1() {
        @Override
        public void call(Integer integer) {
            Log.i(tag, "onNextAction用来处理OnNext()回调的--"+integer);
        }
    };

    Action1 onErrorAction = new Action1() {
        @Override
        public void call(Throwable integer) {
            Log.i(tag, "onNextAction用来处理onError()回调的");
        }
    };
    Action0 onCompletedAction = new Action0() {
        @Override
        public void call() {
            Log.i(tag, "onNextAction用来处理onCompleted()回调的");
        }
    };
}
第三步:创建Observable被观察者

创建方式有如下三种:

  • Observable.create()
  • Observable.from
  • Observable.just()

使用Observable.create()创建Observable代码如下

Observable observable = Observable.create(new Observable.OnSubscribe() {
    @Override
    public void call(Subscriber subscriber) {
        subscriber.onNext("你好1");
        subscriber.onNext("你好2");
        subscriber.onNext("你好3");
        subscriber.onCompleted();
    }
});

使用Observable.from()创建Observable代码如下

String[] arrs = new String[]{"你好1","你好2","你好3"};
/**
 * 此方法会依次执行:
 subscriber.onNext("你好1");
 subscriber.onNext("你好2");
 subscriber.onNext("你好3");
 subscriber.onCompleted();
 */
Observable observable1 = Observable.from(arrs);

使用Observable.just()创建Observable代码如下

/**
 * 此方法会依次执行:
 subscriber.onNext("你好11");
 subscriber.onNext("你好22");
 subscriber.onNext("你好33");
 subscriber.onCompleted();
 */
Observable observable2 = Observable.just("你好11","你好22","你好33");
第四步:subscribe订阅(注册)

只有一句代码

observable.subscribe(observer);

Rxjava的订阅过程中使用创建操作符create源码

查看Observable.create()+observable.subscribe(observer)代码执行过程
Rxjava (上)_第1张图片

需要的源码如下:

/*
观察者:决定了触发事件后的处理,只有这三个方法
**/
public interface Observer {
    //通知观察者,被观察者已完成发送,如果被观察者调用了onError,则不会调用此方法
    void onCompleted();
    //如果Observable调用了此方法,那么就不会调用onNext()方法或onCompleted();
    void onError(Throwable e);
    //Observable可能会0次或多次调用此方法,在Observable调用onCompleted()方法之后不会再调用此方法
    void onNext(T t);
}

/**
Subscriber:是Observer的扩展,基本使用方式一样的;除此之外,在使用时Observer总是先转成一个subscriber使用
Subscriber 与 Observer 的不同:
*/
public abstract class Subscriber implements Observer, Subscription {
    //在Subscriber刚开始,事件还未发送之前调用,可用于做一些初始化操作,如数据的清空或重置
    //若准备工作对线程有要求,那么此方法就不合适了,TODO:查看源码看是在哪调用的
    public void onStart() {
        // do nothing by default
    }

    //重写的Subscription中的方法,用于取消订阅的
    @Override
    public final void unsubscribe() {
        subscriptions.unsubscribe();
    }

    //依旧是重写Subscription中的方法,判断当前订阅者是否还在订阅列表中
    //true:则表示此订阅者已经从订阅列表中移除了
   @Override
    public final boolean isUnsubscribed() {
        return subscriptions.isUnsubscribed();
    }
}

/*
被观察者:http://reactivex.io/documentation/observable.html
**/
public class Observable {

    final OnSubscribe onSubscribe;

    protected Observable(OnSubscribe f) {
        this.onSubscribe = f;
    }

    public static  Observable create(OnSubscribe f) {
        return new Observable(RxJavaHooks.onCreate(f));
    }

    public interface OnSubscribe extends Action1> {
        
    }

    //传入参数是Observer类型,最终也会转成Subscriber使用
    public final Subscription subscribe(final Observer observer) {
        if (observer instanceof Subscriber) {
            return subscribe((Subscriber)observer);
        }
        if (observer == null) {
            throw new NullPointerException("observer is null");
        }
        //查看ObserverSubscriber源码可发现,ObserverSubscriber是Subscriber的子类
        return subscribe(new ObserverSubscriber(observer));
    }

    public final Subscription subscribe(Subscriber subscriber) {
        return Observable.subscribe(subscriber, this);
    }

    static  Subscription subscribe(Subscriber subscriber, Observable observable) {
        //...省略代码
        subscriber.onStart();
        //...省略代码
        try {
            RxJavaHooks.onObservableStart(observable, observable.onSubscribe).call(subscriber);
            return RxJavaHooks.onObservableReturn(subscriber);
        } catch (Throwable e) {
            // ...省略代码
            return Subscriptions.unsubscribed();
        }
    }
}
/**
*工具类,包含各种Observable,Single和Completable生命周期相关的钩子点以及调度程序钩子。
*/
public final class RxJavaHooks {
    
    static {
        init();
    }

     static void init() {
        //...省略代码
        initCreate();
    }

    static volatile Func1 onObservableCreate;

    @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
    static void initCreate() {
        onObservableCreate = new Func1() {
            @Override
            public Observable.OnSubscribe call(Observable.OnSubscribe f) {
                return RxJavaPlugins.getInstance().getObservableExecutionHook().onCreate(f);
            }
        };

        //...省略代码
    }

    /**
     * 当Observable创建时,关联上call;
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static  Observable.OnSubscribe onCreate(Observable.OnSubscribe onSubscribe) {
        Func1 f = onObservableCreate;
        if (f != null) {
            //f也就是onObservableCreate
            return f.call(onSubscribe);
        }
        return onSubscribe;
    }
}

public interface Func1 extends Function {
    R call(T t);
}

public interface Action1 extends Action {
    void call(T t);
}

Rxjava的订阅过程中使用创建操作符from源码解析

查看Observable.create()+observable.subscribe(observer)代码执行过程
Rxjava (上)_第2张图片

需要源代码如下

//被观察者
public class Observable {   
    public static  Observable from(T[] array) {
        int n = array.length;
        if (n == 0) {
            return empty();
        } else
        if (n == 1) {
            //注意:当数组中只有一个1元素时,调用的是just(T t) 
            return just(array[0]);
        }
        return create(new OnSubscribeFromArray(array));
    }
}

    //Observable.OnSubscribe的实现类也是Action1的实现类
public final class OnSubscribeFromArray implements OnSubscribe {
    public OnSubscribeFromArray(T[] array) {
        this.array = array;
    }
    @Override
    public void call(Subscriber child) {
        child.setProducer(new FromArrayProducer(child, array));
    }
        //是Producer的实现类
    static final class FromArrayProducer extends AtomicLong implements Producer {

        final Subscriber child;
        final T[] array;

        int index;

        public FromArrayProducer(Subscriber child, T[] array) {
            this.child = child;
            this.array = array;
        }

        @Override
        public void request(long n) {
            if (n < 0) {
                throw new IllegalArgumentException("n >= 0 required but it was " + n);
            }
            if (n == Long.MAX_VALUE) {
                if (BackpressureUtils.getAndAddRequest(this, n) == 0) {
                    fastPath();
                }
            } else
            if (n != 0) {
                if (BackpressureUtils.getAndAddRequest(this, n) == 0) {
                    slowPath(n);
                }
            }
        }

        void fastPath() {
            final Subscriber child = this.child;

            for (T t : array) {
                if (child.isUnsubscribed()) {
                    return;
                }

                child.onNext(t);
            }

            if (child.isUnsubscribed()) {
                return;
            }
            child.onCompleted();
        }

        void slowPath(long r) {
            final Subscriber child = this.child;
            final T[] array = this.array;
            final int n = array.length;

            long e = 0L;
            int i = index;

            for (;;) {

                while (r != 0L && i != n) {
                    if (child.isUnsubscribed()) {
                        return;
                    }

                    child.onNext(array[i]);

                    i++;

                    if (i == n) {
                        if (!child.isUnsubscribed()) {
                            child.onCompleted();
                        }
                        return;
                    }

                    r--;
                    e--;
                }
                //...
            }
        }
    }
}

//观察者
public abstract class Subscriber implements Observer, Subscription{ 
    public void setProducer(Producer p) {
        long toRequest;
        boolean passToSubscriber = false;
        synchronized (this) {
            toRequest = requested;
            producer = p;
            if (subscriber != null) {
                // middle operator ... we pass through unless a request has been made
                if (toRequest == NOT_SET) {
                    // we pass through to the next producer as nothing has been requested
                    passToSubscriber = true;
                }
            }
        }
        // do after releasing lock
        if (passToSubscriber) {
            subscriber.setProducer(producer);
        } else {
            // we execute the request with whatever has been requested (or Long.MAX_VALUE)
            if (toRequest == NOT_SET) {
                producer.request(Long.MAX_VALUE);
            } else {
                producer.request(toRequest);
            }
        }
    }
}

Rxjava的订阅过程中使用创建操作符just源码解析

源码如下

public class Observable {   
    public static  Observable just(T t1, T t2, T t3) {
        return from((T[])new Object[] { t1, t2, t3 });
    }
}
public static  Observable just(final T value) {
    return ScalarSynchronousObservable.create(value);
}

可以看出Observable.just()内部是调用from(当参数数组的长度 >= 2),也就是说都会一次调用Subscriber的onNext()与onCompleted(),just和from执行过程都是一样的。

当数据数组只有1个元素时,跟踪源码发现和form的执行过程相似,只是在Producer的实现类中request()方法内部不再做遍历数组的操作,直接回调onNext() onCompleted(),代码如下

public class Observable {   

    public static  Observable just(final T value) {
        return ScalarSynchronousObservable.create(value);
    }
    
}
public final class ScalarSynchronousObservable extends Observable {
    
    /*表示这个Observable使用的Producer应该是完全的线程安全,这是可能的,但不太可能是多个并发请求将到达just()。
    上面是源码中的翻译;通过跟踪源码发现STRONG_MODE = false
    */
    static final boolean STRONG_MODE;

    public static  ScalarSynchronousObservable create(T t) {
        return new ScalarSynchronousObservable(t);
    }
    protected ScalarSynchronousObservable(final T t) {
        super(RxJavaHooks.onCreate(new JustOnSubscribe(t)));
        this.t = t;
    }

    static final class JustOnSubscribe implements OnSubscribe {
        final T value;

        JustOnSubscribe(T value) {
            this.value = value;
        }

        @Override
        public void call(Subscriber s) {
            s.setProducer(createProducer(s, value));
        }
    }
    static  Producer createProducer(Subscriber s, T v) {
        if (STRONG_MODE) {
            return new SingleProducer(s, v);
        }
        return new WeakSingleProducer(s, v);
    }
    static final class WeakSingleProducer implements Producer {
        final Subscriber actual;
        final T value;
        boolean once;

        public WeakSingleProducer(Subscriber actual, T value) {
            this.actual = actual;
            this.value = value;
        }

        @Override
        public void request(long n) {
            if (once) {
                return;
            }
            if (n < 0L) {
                throw new IllegalStateException("n >= required but it was " + n);
            }
            if (n == 0L) {
                return;
            }
            once = true;
            Subscriber a = actual;
            if (a.isUnsubscribed()) {
                return;
            }
            T v = value;
                //不需要再遍历了
            try {
                a.onNext(v);
            } catch (Throwable e) {
                Exceptions.throwOrReport(e, a, v);
                return;
            }

            if (a.isUnsubscribed()) {
                return;
            }
            a.onCompleted();
        }
    }
}

Rxjava的不完全回调源码

查看不完全回调代码执行过程
Rxjava (上)_第3张图片

代码如下

//不完全回调部分
public class Observable {   
    public final Subscription subscribe(final Action1 onNext) {
        if (onNext == null) {
            throw new IllegalArgumentException("onNext can not be null");
        }

        Action1 onError = InternalObservableUtils.ERROR_NOT_IMPLEMENTED;
        Action0 onCompleted = Actions.empty();
        return subscribe(new ActionSubscriber(onNext, onError, onCompleted));
    }
    public final Subscription subscribe(final Action1 onNext, final Action1 onError) {
        if (onNext == null) {
            throw new IllegalArgumentException("onNext can not be null");
        }
        if (onError == null) {
            throw new IllegalArgumentException("onError can not be null");
        }
        //跟踪源码,发现Actions.empty()保证了onCompleted != null
        Action0 onCompleted = Actions.empty();
        return subscribe(new ActionSubscriber(onNext, onError, onCompleted));
    }
    public final Subscription subscribe(final Action1 onNext, final Action1 onError, final Action0 onCompleted) {
        if (onNext == null) {
            throw new IllegalArgumentException("onNext can not be null");
        }
        if (onError == null) {
            throw new IllegalArgumentException("onError can not be null");
        }
        if (onCompleted == null) {
            throw new IllegalArgumentException("onComplete can not be null");
        }

        return subscribe(new ActionSubscriber(onNext, onError, onCompleted));
    }
}
//看类名的命名也看出是Subscriber的子类了
public final class ActionSubscriber extends Subscriber {

    final Action1 onNext;
    final Action1 onError;
    final Action0 onCompleted;

    public ActionSubscriber(Action1 onNext, Action1 onError, Action0 onCompleted) {
        this.onNext = onNext;
        this.onError = onError;
        this.onCompleted = onCompleted;
    }

    @Override
    public void onNext(T t) {
        onNext.call(t);
    }

    @Override
    public void onError(Throwable e) {
        onError.call(e);
    }

    @Override
    public void onCompleted() {
        onCompleted.call();
    }
}
思考:不完全回调的写法会不会导致内存泄漏?

Rxjava的Subject

参考地址:
http://gank.io/post/560e15be2dca930e00da1083#toc_1

你可能感兴趣的:(Rxjava (上))