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

还是把demo贴过来

BehaviorSubject<Integer> s = BehaviorSubject.create(555);
        s.subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                System.out.println("1----" + integer);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                System.out.println("onError");
            }
        }, new Action0() {
            @Override
            public void call() {
                System.out.println("onComplete1");
            }
        });
        System.out.println("------1------");
        s.onNext(1);
        System.out.println("--------2----");
        s.onNext(2);
        System.out.println("-------3-----");
        s.subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                System.out.println("2----" + integer);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                System.out.println("onError");
            }
        }, new Action0() {
            @Override
            public void call() {
                System.out.println("onComplete2");
            }
        });
        System.out.println("----4-------");
        s.onNext(3);
        System.out.println("----5--------");
        s.onNext(4);

        System.out.println("-----6-------");
        s.subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                System.out.println("3----" + integer);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                System.out.println("onError");
            }
        }, new Action0() {
            @Override
            public void call() {
                System.out.println("3onComplete");
            }
        });
        s.onCompleted();
类图

还是先看一下create函数

    public static <T> BehaviorSubject<T> create(T defaultValue) {
        return create(defaultValue, true);
    }
    private static <T> BehaviorSubject<T> create(T defaultValue, boolean hasDefault) {
        final SubjectSubscriptionManager<T> state = new SubjectSubscriptionManager<T>();
        if (hasDefault) {
            state.setLatest(NotificationLite.next(defaultValue));
        }
        state.onAdded = new Action1<SubjectObserver<T>>() {

            @Override
            public void call(SubjectObserver<T> o) {
                o.emitFirst(state.getLatest());
            }

        };
        state.onTerminated = state.onAdded;
        return new BehaviorSubject<T>(state, state);
    }
把defaultValue设置到state,设置了state的onAdded

然后subscrib的时候根据前文分析会调用到SubjectSubscriptionManager的call函数,最终又调用到State的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);
    }
这里会回调我们的onAdded,onAdded就是前面设置的

   public void call(SubjectObserver<T> o) {
                o.emitFirst(state.getLatest());
            }
之类state.getLatest()就是我们刚设置的默认值

o则是SubjectObserver

看一下emitFirst函数

void emitFirst(Object n) {
            synchronized (this) {
                if (!first || emitting) {
                    return;
                }
                first = false;
                emitting = n != null;
            }
            if (n != null) {
                emitLoop(null, n);
            }
        }

第一次进来emitting=false,first=true

这里会把emitting设置为true,first设置为false

进入emitLoop

 void emitLoop(List<Object> localQueue, Object current) {
            boolean once = true;
            boolean skipFinal = false;
            try {
                do {
                    if (localQueue != null) {
                        for (Object n : localQueue) {
                            accept(n);
                        }
                    }
                    if (once) {
                        once = false;
                        accept(current);
                    }
                    synchronized (this) {
                        localQueue = queue;
                        queue = null;
                        if (localQueue == null) {
                            emitting = false;
                            skipFinal = true;
                            break;
                        }
                    }
                } while (true);
            } finally {
                if (!skipFinal) {
                    synchronized (this) {
                        emitting = false;
                    }
                }
            }
        }

localQueue为Null

once为true调用accept,并把once设置为false

        void accept(Object n) {
            if (n != null) {
                NotificationLite.accept(actual, n);
            }
        }
这里的actual就是我们的订阅者

public static <T> boolean accept(Observer<? super T> o, Object n) {
        if (n == ON_COMPLETED_SENTINEL) {
            o.onCompleted();
            return true;
        } else if (n == ON_NEXT_NULL_SENTINEL) {
            o.onNext(null);
            return false;
        } else if (n != null) {
            if (n.getClass() == OnErrorSentinel.class) {
                o.onError(((OnErrorSentinel) n).e);
                return true;
            }
            o.onNext((T) n);
            return false;
        } else {
            throw new IllegalArgumentException("The lite notification can not be null");
        }
    }


这里走第二个else if分支,调用onNext

最终调用到demo中我们onNext函数

 public void call(Integer integer) {
                    System.out.println("1----" + integer);
                }

这样subscribe时就把默认值打印出来了

 接着再分享onNext

    public void onNext(T v) {
        Object last = state.getLatest();
        if (last == null || state.active) {
            Object n = NotificationLite.next(v);
            for (SubjectObserver<T> bo : state.next(n)) {
                bo.emitNext(n);
            }
        }
    }

这里last是前面的默认值,active为true

调用state的next

  SubjectObserver<T>[] next(Object n) {
        setLatest(n);
        return get().observers;
    }
设置当前值到state,返回当前的observers,这里就是我们前面订阅的一个

回到onNext调用emitNext

void emitNext(Object n) {
            if (!fastPath) {
                synchronized (this) {
                    first = false;
                    if (emitting) {
                        if (queue == null) {
                            queue = new ArrayList<Object>();
                        }
                        queue.add(n);
                        return;
                    }
                }
                fastPath = true;
            }
            NotificationLite.accept(actual, n);
        }
fastPath为false

最终调用

NotificationLite.accept(actual, n)
这个我们前面分析过

最后看一下onCompleted

    public void onCompleted() {
        Object last = state.getLatest();
        if (last == null || state.active) {
            Object n = NotificationLite.completed();
            for (SubjectObserver<T> bo : state.terminate(n)) {
                bo.emitNext(n);
            }
        }
    }
这里把n设置为NotificationLite.completed(),调用emitNext,后者又调用 NotificationLite.accept(actual, n);

public static <T> boolean accept(Observer<? super T> o, Object n) {
        if (n == ON_COMPLETED_SENTINEL) {
            o.onCompleted();
            return true;
        } else if (n == ON_NEXT_NULL_SENTINEL) {
            o.onNext(null);
            return false;
        } else if (n != null) {
            if (n.getClass() == OnErrorSentinel.class) {
                o.onError(((OnErrorSentinel) n).e);
                return true;
            }
            o.onNext((T) n);
            return false;
        } else {
            throw new IllegalArgumentException("The lite notification can not be null");
        }
    }
n为 NotificationLite.completed()走第一个if分支,最终调用我们的onCompleted



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值