1. 程式人生 > >RxJava2 Flowable forEach (輔助操作符)

RxJava2 Flowable forEach (輔助操作符)

forEach(輔助操作符)

目錄

1 forEach作用和使用場景

同subscribe類似,訂閱Publisher並接其發出的每一個元素的通知,有點遍歷的意思。

2 forEach介面

Disposable forEach(Consumer<? super T> onNext)

Subscribes to the Publisher and receives notifications for each element.

訂閱釋出者並接收每個元素的通知。

Disposable forEachWhile(Predicate<? super T> onNext)

Subscribes to the Publisher and receives notifications for each element until the onNext Predicate returns false.

訂閱釋出者並接收每個元素的通知,直到onNext Predicate返回false。

Disposable forEachWhile(Predicate<? super T> onNext, Consumer<? super Throwable> onError)

Subscribes to the Publisher

 and receives notifications for each element and error events until the onNext Predicate returns false.

訂閱釋出伺服器並接收每個元素和錯誤事件的通知,直到onNext Predicate返回false。

Disposable forEachWhile(Predicate<? super T> onNext, Consumer<? super Throwable> onError,Action onComplete)

Subscribes to the Publisher

 and receives notifications for each element and the terminal events until the onNext Predicate returns false.

訂閱釋出伺服器並接收每個元素和終端事件的通知,直到onNext Predicate返回false。

3 forEach測試用例


測試程式碼
@Test
    public void forEach() {
        System.out.println("######forEach#####");
        Flowable.just("item1", "item2", "item3").forEach(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                System.out.println("s = " + s);
            }
        });

    }


測試結果
######forEach#####
s = item1
s = item2
s = item3