Rxjava(過濾類)-Filter
阿新 • • 發佈:2019-02-16
只發射通過了謂詞測試的資料項
看一下filter函式
predicate就是我們的過濾函式
Observable.range(1, 10).filter(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { return integer % 2 == 0; } }).subscribe(new Action1<Integer>() { @Override public void call(Integer integer) { System.out.println(integer); } });
看一下filter函式
public final Observable<T> filter(Func1<? super T, Boolean> predicate) {
return create(new OnSubscribeFilter<T>(this, predicate));
}
public OnSubscribeFilter(Observable<T> source, Func1<? super T, Boolean> predicate) { this.source = source; this.predicate = predicate; }
predicate就是我們的過濾函式
前面分析可知RangeProducer最終會呼叫
這裡的childSubscriber是FilterSubscribervoid fastPath() { final long endIndex = this.endOfRange + 1L; final Subscriber<? super Integer> childSubscriber = this.childSubscriber; for (long index = currentIndex; index != endIndex; index++) { if (childSubscriber.isUnsubscribed()) { return; } childSubscriber.onNext((int) index); } if (!childSubscriber.isUnsubscribed()) { childSubscriber.onCompleted(); } }
public void onNext(T t) {
boolean result;
try {
result = predicate.call(t);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
unsubscribe();
onError(OnErrorThrowable.addValueAsLastCause(ex, t));
return;
}
if (result) {
actual.onNext(t);
} else {
request(1);
}
}
呼叫過濾函式獲取過濾結果,如果為true才呼叫onNext,達到過濾效果