RxRelay源码解析:
RxRelay源码地址
自定义RxBus + RxRelay
Relays 是既是Observable也是Consumer的RxJava 类型,由于没有onComplete 或 onError,所以发生异常时不会触发下游的终止状态,不会抛出异常。
//接收订阅之后数据
Relay relay = PublishRelay.create().toSerialized();
//接受订阅之前一个和之后数据
Relay relay = BehaviorRelay.createDefault("Hello World");
//不管何时订阅,发送所有数据
Relay relay = ReplayRelay.create(5).toSerialized();
/**
* 队列,用于存储带发射的值
*/
class AppendOnlyLinkedArrayList<T> {
private final int capacity; //容量
private final Object[] head; //用于存放值
private Object[] tail;
private int offset; //数组指针
/**
* 指定容量,初始化数组为容量大小
*/
AppendOnlyLinkedArrayList(int capacity) {
this.capacity = capacity;
this.head = new Object[capacity + 1];
this.tail = head;
}
/**
* 向队列插入值
*/
void add(T value) {
final int c = capacity;
int o = offset;
//若容量满了,创建新数组tail,新数组开始位置指向head末尾,向新数组tail[0]插入值
if (o == c) {
Object[] next = new Object[c + 1];
tail[c] = next;
tail = next;
o = 0;
}
//容量未满,按偏移量插入值
tail[o] = value;
offset = o + 1;
}
/**
* 自定义条件
*/
public interface NonThrowingPredicate<T> extends Predicate<T> {
@Override
boolean test(T t);
}
/**
* 便利队列中所有数组,遇到空或返回条件为真退出
*/
@SuppressWarnings("unchecked")
void forEachWhile(NonThrowingPredicate<? super T> consumer) {
Object[] a = head;
final int c = capacity;
while (a != null) {
for (int i = 0; i < c; i++) {
Object o = a[i];
if (o == null) {
break;
}
if (consumer.test((T)o)) {
break;
}
}<