仅当满足特定的布尔值时,才使Observable返回

问题描述 投票:0回答:1

我有此代码:

    int finalAttempts = attempts;
    Certificate certificate = Observable.range(1, attempts)
            .delay(3, TimeUnit.SECONDS)
            .map(integer -> {
                try {
                    order.update();
                    if(order.getStatus() != Status.VALID) {
                        if(integer == finalAttempts) {
                            Exceptions.propagate(new AcmeException("Order failed... Giving up."));
                        }
                    } else if(order.getStatus() == Status.VALID) {
                        Certificate cert = order.getCertificate();
                        return cert;
                    }
                } catch (AcmeException e) {
                    Exceptions.propagate(e);
                }
                return null; // return only if this is TRUE: order.getStatus() == Status.VALID
            }).toBlocking().first();

我想知道在Observable仍然不为真时阻止此order.getStatus() == Status.VALID完全返回的最佳方法。同时,如果所有尝试或尝试都已被使用,并且状态仍然为true,则应引发异常。

java rx-java rx-java2
1个回答
0
投票

我不知道一个能够完全阻止可观察对象返回的运算符。

filter()运算符在这种情况下可能是您的朋友,如果不满足条件,则会导致可观察到的空白。我想到这样的事情:

int finalAttempts = attempts;
Certificate certificate = Observable.range(1, attempts)
        .delay(3, TimeUnit.SECONDS)
        .filter(integer -> {
            order.update();
            return order.getStatus() == Status.VALID;
        })
        .map(integer -> {

            // do your stuff

        }).toBlocking().first();

我认为您想要的是跳过所有没有order.getStatus() == Status.VALID的事件。但是我在rxJava中没有这样的运算符。有skipWhile(),但是在第一个匹配事件之后它将返回所有内容。

© www.soinside.com 2019 - 2024. All rights reserved.