Rxjava(Subject)-AsyncSubject--代码分析

首先我们来看下它的类结构图



从demo分析我们的代码

  AsyncSubject<Integer> subject = AsyncSubject.create();
        subject.subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                System.out.println("" + integer);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                System.out.println("onError");
            }
        }, new Action0() {
            @Override
            public void call() {
                System.out.println("onComplete");
            }
        });
        subject.onNext(0);
        subject.onNext(1);
        subject.onNext(2);
        subject.onError(new Exception("ddd"));
首先看下create函数

    public static <T> AsyncSubject<T> create() {
        final SubjectSubscriptionManager<T> state = new SubjectSubscriptionManager<T>();
        state.onTerminated = new Action1<SubjectObserver<T>>() {
            @Override
            public void call(SubjectObserver<T> o) {
                Object v = state.getLatest();
                if (v == null || NotificationLite.isCompleted(v)) {
                    o.onCompleted();
                } else
                if (NotificationLite.isError(v)) {
                    o.onError(NotificationLite.getError(v));
                } else {
                    o.actual.setProducer(new SingleProducer<T>(o.actual, NotificationLite.<T>getValue(v)));
                }
            }
        };
        return new AsyncSubject<T>(state, state);
    }
这里创建了一个SubjectSubscriptionManager

  public SubjectSubscriptionManager() {
        super(State.EMPTY);
    }
然后new了一个AsyncSubject,传递的都是state,这里 SubjectSubscriptionManager实现了OnSubscribe接口

    protected AsyncSubject(OnSubscribe<T> onSubscribe, SubjectSubscriptionManager<T> state) {
        super(onSubscribe);
        this.state = state;
    }
下一步当我们在demo中调用subscribe时,这里会调用到SubjectSubscriptionManager的call函数
    public void call(final Subscriber<? super T> child) {
        SubjectObserver<T> bo = new SubjectObserver<T>(child);
        addUnsubscriber(child, bo);
        onStart.call(bo);
        if (!child.isUnsubscribed()) {
            if (add(bo) && child.isUnsubscribed()) {
                remove(bo);
            }
        }
    }
创建一个SubjectObserver对chile做了一层包裹,调用onStart说明有新的 观察者 订阅开始

另外一个是调用add函数添加这个观察者

  boolean add(SubjectObserver<T> o) {
        do {
            State oldState = get();
            if (oldState.terminated) {
                onTerminated.call(o);
                return false;
            }
            State newState = oldState.add(o);
            if (compareAndSet(oldState, newState)) {
                onAdded.call(o);
                return true;
            }
        } while (true);
    }
这里terminated为false

调用State的add函数,调用onAdded说明有新的观察者添加

        public State add(SubjectObserver o) {
            SubjectObserver[] a = observers;
            int n = a.length;
            SubjectObserver[] b = new SubjectObserver[n + 1];
            System.arraycopy(observers, 0, b, 0, n);
            b[n] = o;
            return new State<T>(terminated, b);
        }
这里把新的Observer添加进去,创建一个新的State


回到demo ,onNext函数比较简单

  public void onNext(T v) {
        lastValue = NotificationLite.next(v);
    }
最后是onCompleted函数

    @Override
    public void onCompleted() {
        if (state.active) {
            Object last = lastValue;
            if (last == null) {
                last = NotificationLite.completed();
            }
            for (SubjectObserver<T> bo : state.terminate(last)) {
                if (last == NotificationLite.completed()) {
                    bo.onCompleted();
                } else {
                    bo.actual.setProducer(new SingleProducer<T>(bo.actual, NotificationLite.<T>getValue(last)));
                }
            }
        }
    }

判断state是否active,state只有在 terminate时active才会为false

获取最后一个值

    SubjectObserver<T>[] terminate(Object n) {
        setLatest(n);
        active = false;

        State<T> oldState = get();
        if (oldState.terminated) {
            return State.NO_OBSERVERS;
        }
        return getAndSet(State.TERMINATED).observers;
    }
调用state的 terminate结束当前状态,并返回当前状态的observers,这里的 observers就是我们前面添加的


回到onComplete如果不是NotificationLite,调用setProducer,这里新建一个SingleProducer,最终会调用SingleProducer的request

 public void request(long n) {
        // negative requests are bugs
        if (n < 0) {
            throw new IllegalArgumentException("n >= 0 required");
        }
        // we ignore zero requests
        if (n == 0) {
            return;
        }
        // atomically change the state into emitting mode
        if (compareAndSet(false, true)) {
            // avoid re-reading the instance fields
            final Subscriber<? super T> c = child;
            // eagerly check for unsubscription
            if (c.isUnsubscribed()) {
                return;
            }
            T v = value;
            // emit the value
            try {
                c.onNext(v);
            } catch (Throwable e) {
                Exceptions.throwOrReport(e, c, v);
                return;
            }
            // eagerly check for unsubscription
            if (c.isUnsubscribed()) {
                return;
            }
            // complete the child
            c.onCompleted();
        }
    }

这里最终会调用到我们demo中Subscriber的onNext和onCompleted




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值