将可以抛出的代码转换为 Rxjava
Convert code with that can throw to Rxjava
我有以下代码
private void tryToLauch() {
try {
launch();
} catch (MyException e) {
postError(e.getErrorMessage());
e.printStackTrace();
}
}
如何将其转换为在出现异常时会在一段时间内重试的 Rx?
鉴于您的方法具有 return 类型的 void,我建议您使用 Completable。
您可以尝试这个解决方案,使用 RxJava 2
Completable myCompletable = Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
launch();
}
}).retry(3 /*number of times to retry*/, new Predicate<Throwable>() {
@Override
public boolean test(Throwable throwable) throws Exception {
return throwable instanceof MyException;
}
});
然后订阅 Completable
myCompletable.subscribeOn(SubscribeScheduler)
.observeOn(ObserveScheduler)
.subscribe(this::onComplete, this::onError);
希望对您有所帮助。
我有以下代码
private void tryToLauch() {
try {
launch();
} catch (MyException e) {
postError(e.getErrorMessage());
e.printStackTrace();
}
}
如何将其转换为在出现异常时会在一段时间内重试的 Rx?
鉴于您的方法具有 return 类型的 void,我建议您使用 Completable。
您可以尝试这个解决方案,使用 RxJava 2
Completable myCompletable = Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
launch();
}
}).retry(3 /*number of times to retry*/, new Predicate<Throwable>() {
@Override
public boolean test(Throwable throwable) throws Exception {
return throwable instanceof MyException;
}
});
然后订阅 Completable
myCompletable.subscribeOn(SubscribeScheduler)
.observeOn(ObserveScheduler)
.subscribe(this::onComplete, this::onError);
希望对您有所帮助。