RetryWhen与Single一起使用时出现一些问题 [英] RetryWhen is giving some issues when using with Single

查看:390
本文介绍了RetryWhen与Single一起使用时出现一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用改型打API调用并接收该调用的响应.我正在使用Rxjava的Single来获取响应.我需要做的是,如果呼叫失败,请重试. 我已经看了很多例子,但是似乎没有什么帮助(也是由于我对RXjava和Kotlin的了解有限).

I am trying to hit an API call using retrofit and receive the response from the call. I am using the Single of Rxjava to get the response. What I need to do is that a retry if the call fails. I have gone through lots of examples but it seems none could have been a help (Also because of my limited knowledge on RXjava and Kotlin).

下面是执行调用的函数和我编写的retryWhen函数

Below is the function which does the call and the retryWhen function I wrote

fun testFetch(): Single<ResponseBody>{
    return retrofitService.getCTLNetworkService().test().retryWhen {
        val ato = AtomicInteger()
        it.takeWhile {
            ato.incrementAndGet() < 4
        }.flatMap {
            Flowable.timer(1, TimeUnit.MINUTES)
        }
    }
}

这正是我想要实现的目标

This is exactly what I want to achieve

  Single.timer(1, TimeUnit.SECONDS)
 *     .doOnSubscribe(s -&gt; System.out.println("subscribing"))
 *     .map(v -&gt; { throw new RuntimeException(); })
 *     .retryWhen(errors -&gt; {
 *         AtomicInteger counter = new AtomicInteger();
 *         return errors
 *                   .takeWhile(e -&gt; counter.getAndIncrement() != 3)
 *                   .flatMap(e -&gt; {
 *                       System.out.println("delay retry by " + counter.get() + " second(s)");
 *                       return Flowable.timer(counter.get(), TimeUnit.SECONDS);
 *                   });
 *     })
 *     .blockingGet();

下面是我编译代码时的错误

Below is the error when I compile the code

Type mismatch: inferred type is (Throwable!) -> Flowable<Long!>! but ((Throwable!) -> Publisher!)! was expected

注意:为简单起见,更改了方法.甚至没有任何映射器和模型的简单signle<ResponseBody>调用也会失败

NOTE: Changed the method for simplicity. Even a simple signle<ResponseBody> call without any mapper and model fails

推荐答案

选中此要点链接

以下是使用扩展程序的示例

Here is example how to use extension

// import extension file 
import com.vk.extension.retryWhenError
 // example
 Observable.fromIterable<Int>(Arrays.asList(1, 2, 3)).retryWhen { it.retryWhenError()}
        .subscribe { integers: Int -> Log.d(TAG, "item $integers") }

这篇关于RetryWhen与Single一起使用时出现一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆