RxJava2 Flowable elementAt elementAtOrError (过滤操作符)

elementAt

目录

1 elementAt作用

2 elementAt接口

3 elementAt图解说明

4 elementAt测试用例

5 使用场景


1 elementAt作用

指定一个索引位置,如果这个索引在发射源Publisher发射的所有项目的索引里,则指定发射这个索引位置的项目,有点定位发射的意思。

 

2 elementAt接口

Maybe<T> elementAt(long index)

Returns a Maybe that emits the single item at a specified index in a sequence of emissions from this Flowable or completes if this Flowable sequence has fewer elements than index.

返回一个Maybe,它在此Flowable的一系列排放中的指定索引处发出单个项目,或者如果此Flowable序列的元素少于索引则完成。

Single<T> elementAt(long index, T defaultItem)

Returns a Flowable that emits the item found at a specified index in a sequence of emissions from this Flowable, or a default item if that index is out of range.

返回一个Flowable,它发出在此Flowable发射的项目中指定索引处找到的项目,或者如果该索引超出范围则返回默认项目。

Single<T> elementAtOrError(long index)

Returns a Flowable that emits the item found at a specified index in a sequence of emissions from this Flowable or signals a NoSuchElementException if this Flowable has fewer elements than index.

返回一个Flowable,它发出在此Flowable发射的项目中指定索引处找到的项目,或者如果此Flowable的元素少于索引,则发出NoSuchElementException信号。

 

3 elementAt图解说明

指定发射索引为2的项目

RxJava2 Flowable elementAt elementAtOrError (过滤操作符)

 

4 elementAt测试用例

下面测试用例使用elementAt操作符发射源Publisher发射的项目中索引为3的项目item8,有点定位发射意思,就是指定发射索引为3的项目


    @Test
    public void elementAt() {
        System.out.println("######elementAt#####");
        Flowable.just("item2", "item1", "item7", "item8", "item9").elementAt(3L).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                System.out.println("s = " + s);
            }
        });
    }

测试输出
######elementAt#####
s = item8

 

5 使用场景

比如android做一个list列表,要求奇数位置的背景色跟偶数位置的背景色不同