1. 程式人生 > >RxJava2 Flowable first 、last (過濾操作符)

RxJava2 Flowable first 、last (過濾操作符)

測試程式碼
@Test
    public void first() {
        System.out.println("######first#####");
        System.out.println("測試1:源Publisher不為空");
        Flowable.just("item2", "item1", "item7").first("item0").subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                System.out.println("s = " + s);
            }
        });

        System.out.println("測試2:源Publisher為空,first發射預設值");
        Flowable.empty().first("item0").subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                System.out.println("o = " + o.toString());
            }
        });

        System.out.println("測試3:源Publisher為空,發射錯誤訊號");
        Flowable.empty().firstOrError().subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                System.out.println("o = " + o.toString());
            }
        });
    }



測試結果:
######first#####
測試1:源Publisher不為空
s = item2
測試2:源Publisher為空,first發射預設值
o = item0
測試3:源Publisher為空,發射錯誤訊號
java.util.NoSuchElementException