在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實現錯誤處理。你可以根據需要選擇合適的錯誤處理策略。