// observer will receive all 4 events (including "default").
BehaviorSubject
所有case都通过上述代码进行了分析,我们看下图:
BehaviorSubject
原理
我们简单看一下BehaviorSubject内部的几个成员:
public final class BehaviorSubject extends Subject {
private static final Object[] EMPTY_ARRAY = new Object[0];
//原子操作类,当前接收到的最后一个数据
final AtomicReference value;
//原子操作类,BehaviorDisposable内部存储了所有接受到的数据
final AtomicReference[]> subscribers;
//标记,意味着一个空的BehaviorDisposable
static final BehaviorDisposable[] EMPTY = new BehaviorDisposable[0];
//标记,意味着已经达到了TERMINATED,终止数据的发射
static final BehaviorDisposable[] TERMINATED = new BehaviorDisposable[0];
...
}
我们再来看一下BehaviorDisposable:
static final class BehaviorDisposable implements Disposable, NonThrowingPredicate {
...
//实际上内部有一个List,存储所有接收到的数据
AppendOnlyLinkedArrayList queue;
...
}
PublishSubject subject = PublishSubject.create();
// observer1 will receive all onNext and onComplete events
subject.subscribe(observer1);
subject.onNext("one");
subject.onNext("two");
// observer2 will only receive "three" and onComplete
subject.subscribe(observer2);
subject.onNext("three");
subject.onComplete();
public final class PublishSubject extends Subject {
static final PublishDisposable[] TERMINATED = new PublishDisposable[0];
static final PublishDisposable[] EMPTY = new PublishDisposable[0];
final AtomicReference[]> subscribers;
}
static final class PublishDisposable extends AtomicBoolean implements Disposable {
}
public final class AsyncSubject extends Subject {
static final AsyncDisposable[] EMPTY = new AsyncDisposable[0];
static final AsyncDisposable[] TERMINATED = new AsyncDisposable[0];
final AtomicReference[]> subscribers;
//记录最新的数据
T value;
}
//继承DeferredScalarDisposable
static final class AsyncDisposable extends DeferredScalarDisposable {}
//继承BasicIntQueueDisposable
public class DeferredScalarDisposable extends BasicIntQueueDisposable {}
//继承AtomicInteger
public abstract class BasicIntQueueDisposable
extends AtomicInteger
implements QueueDisposable {}
public final void complete(T value) {
//......
Observer super T> a = actual;
//先发送最后一个数据
a.onNext(value);
if (get() != DISPOSED) {
//执行onComplete()
a.onComplete();
}
}
public abstract class Subject extends Observable implements Observer {
//......
public final Subject toSerialized() {
if (this instanceof SerializedSubject) {
return this;
}
return new SerializedSubject(this);
}
}
原题链接:#137 Single Number II
要求:
给定一个整型数组,其中除了一个元素之外,每个元素都出现三次。找出这个元素
注意:算法的时间复杂度应为O(n),最好不使用额外的内存空间
难度:中等
分析:
与#136类似,都是考察位运算。不过出现两次的可以使用异或运算的特性 n XOR n = 0, n XOR 0 = n,即某一
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, det