简体   繁体   English

装饰可观察

[英]Decorating observable

Is it OK to decorate Observable<> , Single<> , Maybe<> , Flowable<> in rx-java? 可以在rx-java中修饰Observable<>Single<>Maybe<>Flowable<>吗?
Eg like this: 像这样:

public final class NonEmptyStringSource extends Observable<String> {

    private final Observable<String> source;

    public NonEmptyStringSource(final Observable<String> source) {
        this.source = source.filter(s -> s.length() > 0);
    }

    @Override
    protected void subscribeActual(final Observer<? super String> observer) {
        this.source.subscribe(observer);
    }
}

Does this approach have some pitfalls? 这种方法有一些陷阱吗?
Is it safe in use? 使用安全吗?

Unlike 1.x, this pattern in 2.x has no penalty and is almost like how the standard operators are implemented. 与1.x不同,2.x中的这种模式没有惩罚,几乎与标准运算符的实现方式相同。 Depending on your needs, you may want to implement an ObservableTransformer instead: 根据您的需要,您可能希望实现ObservableTransformer

ObservableTransformer<String, String> t = 
    upstream -> upstream.filter(s -> s.length() > 0);

Observable.fromArray("a", "b", "", "d", "", "f")
.compose(t)
.subscribe(System.out::println, Throwable::printStackTrace);

I would advise against this, as it just obfuscates what is actually going on. 我建议不要这样做,因为它只是模糊了实际发生的事情。

Just using filter inline is cleaner and more readable: 只使用filter内联更清晰,更易读:

 .filter(StringUtils::isNotBlank)

This comes from Apache Commons-Lang, but you can roll your own implementation just as easily. 这来自Apache Commons-Lang,但您可以轻松地实现自己的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM