在Java中,使用RxJava库可以轻松地实现响应式编程
import io.reactivex.Observable;
public class RxJavaErrorHandling {
public static void main(String[] args) {
Observable<String> observable = Observable.create(emitter -> {
emitter.onNext("Hello");
emitter.onNext("World");
// 抛出一个异常
throw new RuntimeException("An error occurred!");
});
}
}
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
public class RxJavaErrorHandling {
public static void main(String[] args) {
Observable<String> observable = Observable.create(emitter -> {
emitter.onNext("Hello");
emitter.onNext("World");
// 抛出一个异常
throw new RuntimeException("An error occurred!");
});
Observer<String> observer = new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
System.out.println("Subscribed");
}
@Override
public void onNext(String s) {
System.out.println("Received: " + s);
}
@Override
public void onError(Throwable e) {
System.err.println("Error: " + e.getMessage());
}
@Override
public void onComplete() {
System.out.println("Completed");
}
};
observable.subscribe(observer);
}
}
运行上面的代码,你将看到以下输出:
Subscribed
Received: Hello
Received: World
Error: An error occurred!
注意,onComplete()
方法不会被调用,因为在发送数据之后发生了错误。
onErrorReturn
操作符处理错误并返回一个默认值:import io.reactivex.Observable;
public class RxJavaErrorHandling {
public static void main(String[] args) {
Observable<String> observable = Observable.create(emitter -> {
emitter.onNext("Hello");
emitter.onNext("World");
// 抛出一个异常
throw new RuntimeException("An error occurred!");
});
observable.onErrorReturn(throwable -> "Default value")
.subscribe(
s -> System.out.println("Received: " + s),
e -> System.err.println("Error: " + e.getMessage()),
() -> System.out.println("Completed")
);
}
}
运行上面的代码,你将看到以下输出:
Received: Hello
Received: World
Received: Default value
Completed
onErrorResumeNext
操作符处理错误并继续发送数据:import io.reactivex.Observable;
public class RxJavaErrorHandling {
public static void main(String[] args) {
Observable<String> observable = Observable.create(emitter -> {
emitter.onNext("Hello");
emitter.onNext("World");
// 抛出一个异常
throw new RuntimeException("An error occurred!");
});
observable.onErrorResumeNext(throwable -> Observable.just("Resumed value"))
.subscribe(
s -> System.out.println("Received: " + s),
e -> System.err.println("Error: " + e.getMessage()),
() -> System.out.println("Completed")
);
}
}
运行上面的代码,你将看到以下输出:
Received: Hello
Received: World
Received: Resumed value
Completed
这些示例展示了如何在Java中使用RxJava实现错误处理。你可以根据需要选择合适的错误处理策略。