RxJava 只检查第一个超时的响应项 [英] RxJava only check the first response item with timeout

查看:33
本文介绍了RxJava 只检查第一个超时的响应项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 ReactiveX (RxJava) 有一个运算符 timeout,它将应用于订阅流中的每个项目.但我只想用超时检查第一个响应,而不关心以下响应的超时.如何使用 RxJava 的运算符优雅地实现此要求?

I see that ReactiveX (RxJava) has an operator timeout, which will apply to every item in a subscription stream. But I only want to check the very first response with a timeout and do not care about timeouts for the following responses. How can I implement this requirement elegantly with RxJava's operators?

推荐答案

最好的选择是使用 超时重载,它为每个项目返回一个超时观察值,并且也有一个用于订阅(这是你有兴趣).

Best option is to use a timeout overload which returns a timeout observable for every item, and has one for the subscription as well (which is the one you are interested in).

observable.timeout(
  () -> Observable.empty().delay(10, TimeUnit.SECONDS),
  o -> Observable.never()
)

我会解释一下,第一个 func0 将在 subscribe 时运行,并会在您想要的时间延迟后发出一个空的 observable(发出完整的).如果在任何物品到达之前时间过去了,就会像您想要的那样超时.第二个参数 func1 将决定项目之间的超时时间,你没有用,所以我们只传递 never(它不完成或做任何事情)

I'll explain, the first func0 will run on subscribe, and will emit an empty observable (which emits complete) delayed by the time you want. if the time passes before any item arrived there will be a timeout like you wanted. the second parameter func1 will decide timeouts between items, which you have no use for so we just passes never (which does not complete or do anything)

另一种选择是按照 Luciano 的建议,你可以这样做:

Another option is following Luciano suggestion, you can do it like this:

    public static class TimeoutFirst<T> implements Transformer<T,T> {

    private final long timeout;
    private final TimeUnit unit;

    private TimeoutFirst(long timeout, TimeUnit unit) {
        this.timeout = timeout;
        this.unit = unit;
    }

    @Override
    public Observable<T> call(Observable<T> observable) {
        return Observable.amb(observable,
                Observable.timer(timeout, unit).flatMap(aLong -> Observable.error(new TimeoutException("Timeout after " + timeout + " "  + unit.name()))));
    }
}

public static <T> Transformer<T, T> timeoutFirst(long timeout, TimeUnit seconds) {
    return new TimeoutFirst<>(timeout, seconds);
}

这是一个使用 amb 的非常简洁的解决方案.

which is a pretty neat solution using amb.

这篇关于RxJava 只检查第一个超时的响应项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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