- Learning RxJava
- Thomas Nield
- 265字
- 2021-07-02 22:22:54
Single
Single<T> is essentially an Observable<T> that will only emit one item. It works just like an Observable, but it is limited only to operators that make sense for a single emission. It has its own SingleObserver interface as well:
interface SingleObserver<T> {
void onSubscribe(Disposable d);
void onSuccess(T value);
void onError(Throwable error);
}
The onSuccess() essentially consolidates onNext() and onComplete() into a single event that accepts the one emission. When you call subscribe() against a Single, you provide the lambdas for onSuccess() as well as an optional onError():
import io.reactivex.Single;
public class Launcher {
public static void main(String[] args) {
Single.just("Hello")
.map(String::length)
.subscribe(System.out::println,
Throwable::printStackTrace);
}
}
Certain RxJava Observable operators will yield a Single, as we will see in the next chapter. For instance, the first() operator will return a Single since that operator is logically concerned with a single item. However, it accepts a default value as a parameter (which I specified as Nil in the following example) if the Observable comes out empty:
import io.reactivex.Observable;
public class Launcher {
public static void main(String[] args) {
Observable<String> source =
Observable.just("Alpha","Beta","Gamma");
source.first("Nil") //returns a Single
.subscribe(System.out::println);
}
}
The output is as follows:
Alpha
The Single must have one emission, and you should prefer it if you only have one emission to provide. This means that instead of using Observable.just("Alpha"), you should try to use Single.just("Alpha") instead. There are operators on Single that will allow you to turn it into an Observable when needed, such as toObservable().
If there are 0 or 1 emissions, you will want to use Maybe.
- Mastering Entity Framework Core 2.0
- MATLAB 2020 從入門到精通
- The Data Visualization Workshop
- 面向?qū)ο蟪绦蛟O(shè)計(jì)(Java版)
- 微信小程序全棧開發(fā)技術(shù)與實(shí)戰(zhàn)(微課版)
- Scala Reactive Programming
- 匯編語言編程基礎(chǔ):基于LoongArch
- Programming with CodeIgniterMVC
- QGIS Python Programming Cookbook(Second Edition)
- Processing創(chuàng)意編程指南
- Emotional Intelligence for IT Professionals
- 深入實(shí)踐DDD:以DSL驅(qū)動(dòng)復(fù)雜軟件開發(fā)
- Android應(yīng)用程序設(shè)計(jì)
- Web前端測(cè)試與集成:Jasmine/Selenium/Protractor/Jenkins的最佳實(shí)踐
- Java面向?qū)ο蟪绦蛟O(shè)計(jì)教程