代码之家  ›  专栏  ›  技术社区  ›  Alexey K

将带有该cat抛出的代码转换为Rxjava

  •  1
  • Alexey K  · 技术社区  · 7 年前

    我有以下代码

    private void tryToLauch() {
            try {
                launch();
            } catch (MyException e) {
                postError(e.getErrorMessage());
                e.printStackTrace();
            }
        }
    

    如何将其转换为Rx,以便在出现异常时在某个时间段内重试?

    0 回复  |  直到 7 年前
        1
  •  2
  •   Cochi    7 年前

    鉴于您的方法具有as 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);
    

    希望这有帮助。