- Learning RxJava
- Thomas Nield
- 299字
- 2021-07-02 22:22:54
Observable.fromCallable()
If you need to perform a calculation or action and then emit it, you can use Observable.just() (or Single.just() or Maybe.just(), which we will learn about later). But sometimes, we want to do this in a lazy or deferred manner. Also, if that procedure throws an error, we want it to be emitted up the Observable chain through onError() rather than throw the error at that location in traditional Java fashion. For instance, if you try to wrap Observable.just() around an expression that divides 1 by 0, the exception will be thrown, not emitted up to Observer:
import io.reactivex.Observable;
public class Launcher {
public static void main(String[] args) {
Observable.just(1 / 0)
.subscribe(i -> System.out.println("RECEIVED: " + i),
e -> System.out.println("Error Captured: " + e));
}
}
The output is as follows:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Launcher.main(Launcher.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke
(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.
invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.
application.AppMain.main(AppMain.java:147)
If we are going to be reactive in our error handling, this may not be desirable. Perhaps you would like the error to be emitted down the chain to the Observer where it will be handled. If that is the case, use Observable.fromCallable() instead, as it accepts a lambda Supplier<T> and it will emit any error that occurs down to Observer:
import io.reactivex.Observable;
public class Launcher {
public static void main(String[] args) {
Observable.fromCallable(() -> 1 / 0)
.subscribe(i -> System.out.println("Received: " + i),
e -> System.out.println("Error Captured: " + e));
}
}
The output is as follows:
Error Captured: java.lang.ArithmeticException: / by zero
That is better! The error was emitted to the Observer rather than being thrown where it occurred. If initializing your emission has a likelihood of throwing an error, you should use Observable.fromCallable() instead of Observable.just().
- Computer Vision for the Web
- Getting Started with ResearchKit
- Effective C#:改善C#代碼的50個(gè)有效方法(原書第3版)
- React Native Cookbook
- Spring Boot+Spring Cloud+Vue+Element項(xiàng)目實(shí)戰(zhàn):手把手教你開發(fā)權(quán)限管理系統(tǒng)
- Animate CC二維動(dòng)畫設(shè)計(jì)與制作(微課版)
- 高級(jí)C/C++編譯技術(shù)(典藏版)
- Mastering Yii
- Mastering Predictive Analytics with Python
- INSTANT Django 1.5 Application Development Starter
- 機(jī)器學(xué)習(xí)與R語言實(shí)戰(zhàn)
- Mastering Elixir
- Python自然語言理解:自然語言理解系統(tǒng)開發(fā)與應(yīng)用實(shí)戰(zhàn)
- App Inventor少兒趣味編程動(dòng)手做
- 30天學(xué)通C#項(xiàng)目案例開發(fā)