不同的是,take(1)将从上游中继0..1项,而如果上游为空,则首先将中继第一个元素或发出错误(NoSuchElementException).他们都没有阻止.
这是真的第一个== take(1).single()其中take(1)将上游项的数量限制为1,而单()使上游不为空.
此示例仅打印“完成”
Observable.empty().take(1)
.subscribe(System.out::println, Throwable::printStackTrace,
() -> System.out.println("Done"));
此示例打印“1”,后跟“完成”:
Observable.just(1).take(1)
.subscribe(System.out::println, Throwable::printStackTrace,
() -> System.out.println("Done"));
此示例还打印“1”,后跟“完成”:
Observable.just(1, 2, 3).take(1)
.subscribe(System.out::println, Throwable::printStackTrace,
() -> System.out.println("Done"));
此示例与NoSuchElementException失败
Observable.empty().first()
.subscribe(System.out::println, Throwable::printStackTrace,
() -> System.out.println("Done"));
此示例再次打印“1”,后跟“完成”:
Observable.just(1).first()
.subscribe(System.out::println, Throwable::printStackTrace,
() -> System.out.println("Done"));
此示例再次打印“1”,后跟“完成”:
Observable.just(1, 2, 3).first()
.subscribe(System.out::println, Throwable::printStackTrace,
() -> System.out.println("Done"));
此示例打印一个NoSuchElementException的堆栈跟踪,因为源包含的元素太少:
Observable.empty().single()
.subscribe(System.out::println, Throwable::printStackTrace,
() -> System.out.println("Done"));
此示例打印IllegalArgumentException的堆栈跟踪,因为源包含太多元素:
Observable.just(1, 2, 3).single()
.subscribe(System.out::println, Throwable::printStackTrace,
() -> System.out.println("Done"));