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

  • Learning RxJava
  • Thomas Nield
  • 262字
  • 2021-07-02 22:22:51

Using Observable.just()

Before we look at the subscribe() method a bit more, note that you likely will not need to use Observable.create() often. It can be helpful in hooking into certain sources that are not reactive, and we will see this in a couple of places later in this chapter. But typically, we use streamlined factories to create Observables for common sources.

In our previous example with Observable.create(), we could have used Observable.just() to accomplish this. We can pass it up to 10 items that we want to emit. It will invoke the onNext() call for each one and then invoke onComplete() when they all have been pushed:

    import io.reactivex.Observable;

public class Launcher {
public static void main(String[] args) {
Observable<String> source =
Observable.just("Alpha", "Beta", "Gamma", "Delta",
"Epsilon");

source.map(String::length).filter(i -> i >= 5)
.subscribe(s -> System.out.println("RECEIVED: " + s));
}
}

We can also use Observable.fromIterable() to emit the items from any Iterable type, such as a List. It also will call onNext() for each element and then call onComplete() after the iteration is complete. You will likely use this factory frequently since Iterables in Java are common and can easily be made reactive:

    import io.reactivex.Observable;
import java.util.Arrays;
import java.util.List;

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

List<String> items =
Arrays.asList("Alpha", "Beta", "Gamma", "Delta", "Epsilon");

Observable<String> source = Observable.fromIterable(items);
source.map(String::length).filter(i -> i >= 5)
.subscribe(s -> System.out.println("RECEIVED: " + s));
}
}

We will explore other factories to create Observables later in this chapter, but for now, let's put that on hold and learn more about Observers.

主站蜘蛛池模板: 新宾| 湛江市| 谢通门县| 钦州市| 青河县| 达州市| 兴义市| 海口市| 民丰县| 阳曲县| 普陀区| 五家渠市| 江华| 平度市| 利辛县| 镇远县| 金坛市| 高阳县| 乐山市| 长子县| 琼中| 阳西县| 隆昌县| 房产| 灌南县| 松桃| 晋中市| 科技| 贺州市| 娱乐| 左贡县| 宝兴县| 金溪县| 麻城市| 浪卡子县| 香港 | 隆林| 苍南县| 阳西县| 龙海市| 襄汾县|