官术网_书友最值得收藏!

startWith()

For a given Observable<T>, the startWith() operator allows you to insert a T emission that precedes all the other emissions. For instance, if we have an Observable<String>that emits items on a menu we want to print, we can use startWith() to append a title header first:

import io.reactivex.Observable;

public class Launcher {
public static void main(String[] args) {

Observable<String> menu =
Observable.just("Coffee", "Tea", "Espresso", "Latte");

//print menu
menu.startWith("COFFEE SHOP MENU")
.subscribe(System.out::println);

}
}

The output of the preceding code snippet is as follows:

COFFEE SHOP MENU
Coffee
Tea
Espresso
Latte

If you want to start with more than one emission, use startWithArray() to accept varargs parameters. If we want to add a divider between our header and menu items, we can start with both the header and divider as emissions:

import io.reactivex.Observable;

public class Launcher {
public static void main(String[] args) {

Observable<String> menu =
Observable.just("Coffee", "Tea", "Espresso", "Latte");

//print menu
menu.startWithArray("COFFEE SHOP MENU","----------------")
.subscribe(System.out::println);

}
}

The output of the preceding code snippet is as follows:

COFFEE SHOP MENU
----------------
Coffee
Tea
Espresso
Latte

The startWith() operator is helpful for cases like this, where we want to seed an initial value or precede our emissions with one or more emissions.

If you want an entire emissions of Observable to precede emissions of another  Observable, you will want to use Observable.concat() or concatWith(), which we will cover in the next chapter.
主站蜘蛛池模板: 大姚县| 墨江| 定西市| 青龙| 辽宁省| 特克斯县| 右玉县| 抚远县| 华亭县| 大姚县| 车致| 乌兰县| 谢通门县| 巴东县| 德昌县| 阜城县| 台东市| 平陆县| 房产| 古蔺县| 任丘市| 东乡| 山东省| 溧阳市| 广丰县| 宁河县| 阿鲁科尔沁旗| 内丘县| 黄山市| 新平| 遂溪县| 阿拉尔市| 滦平县| 泰兴市| 区。| 临泉县| 内黄县| 江华| 彰化县| 六枝特区| 怀柔区|