抑制Observable发射的后N项数据
demo
Observable.range(1, 10).skipLast(2).subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
System.out.println(integer);
}
});
输出:
1
2
3
4
5
6
7
8
我们看一下skipLast
public final Observable<T> skipLast(int count) {
return lift(new OperatorSkipLast<T>(count));
}
我们看下OperatorSkipLast
public class OperatorSkipLast<T> implements Operator<T, T> {
final int count;
public OperatorSkipLast(int count) {
if (count < 0) {
throw new IndexOutOfBoundsException("count could not be negative");
}
this.count = count;
}
@Override
public Subscriber<? super T> call(final Subscriber<? super T> subscriber) {
return new Subscriber<T>(subscriber) {
/**
* Store the last count elements until now.
*/
private final Deque<Object> deque = new ArrayDeque<Object>();
@Override
public void onCompleted() {
subscriber.onCompleted();
}
@Override
public void onError(Throwable e) {
subscriber.onError(e);
}
@Override
public void onNext(T value) {
if (count == 0) {
// If count == 0, we do not need to put value into deque
// and remove it at once. We can emit the value
// directly.
subscriber.onNext(value);
return;
}
if (deque.size() == count) {
subscriber.onNext(NotificationLite.<T>getValue(deque.removeFirst()));
} else {
request(1);
}
deque.offerLast(NotificationLite.next(value));
}
};
}
}
onNext的逻辑是这样的,count代表忽略末尾的个数
首先如果count是0,表示不忽略,直接调用onNext
如果当前队列的大小已经大道count,则出队列一个并调用onNext,
把当前数据入队列
这样就大道了忽略最后几项