1. 程式人生 > >Rxjava(過濾類)-Filter

Rxjava(過濾類)-Filter

只發射通過了謂詞測試的資料項

 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最終會呼叫

void 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();
            }
        }
這裡的childSubscriber是FilterSubscriber
 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,達到過濾效果