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

  • Learning RxJava
  • Thomas Nield
  • 236字
  • 2021-07-02 22:22:58

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.
主站蜘蛛池模板: 耒阳市| 娱乐| 青浦区| 桂林市| 嘉峪关市| 平乡县| 霍林郭勒市| 休宁县| 洪洞县| 张家口市| 探索| 永昌县| 东源县| 桑植县| 许昌县| 杭锦后旗| 油尖旺区| 昭觉县| 景洪市| 广汉市| 邵武市| 涞水县| 逊克县| 丹凤县| 漳州市| 彭阳县| 大宁县| 绍兴县| 门源| 佛冈县| 榕江县| 广平县| 东莞市| 昌平区| 广元市| 辽宁省| 辉县市| 建德市| 石首市| 珠海市| 五家渠市|