- 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.
- Python 3.7網絡爬蟲快速入門
- Flutter開發實戰詳解
- Mastering RabbitMQ
- SQL Server 2016從入門到精通(視頻教學超值版)
- 軟件界面交互設計基礎
- C++ Builder 6.0下OpenGL編程技術
- x86匯編語言:從實模式到保護模式(第2版)
- Expert Android Programming
- Learning Python by Building Games
- OpenCV 4計算機視覺項目實戰(原書第2版)
- 從零開始學C#
- Unity 3D腳本編程:使用C#語言開發跨平臺游戲
- Hands-On Kubernetes on Windows
- 視窗軟件設計和開發自動化:可視化D++語言
- Kotlin語言實例精解