简体   繁体   English

RxJava接口的Single / Observable返回实现

[英]RxJava Single/Observable return implementation of interface

I have faced with interesting problem 我遇到了有趣的问题

I have the following method 我有以下方法

@Override
public Single<IResults> getResults() {
    return Single.just(new ConcreteResults());
}

IResults is an interface and ConcreteResults is the implementation. IResults是接口, ConcreteResults是实现。

However I am getting an error 但是我遇到一个错误

Error:(149, 27) error: incompatible types: Single<ConcreteResults> cannot be converted to Single<IResults>

How to solve this issue ? 如何解决这个问题? I need to have an interface to abstract return type. 我需要一个接口来抽象返回类型。

However, this dirty trick seems to work :) 但是,这个肮脏的把戏似乎有效:)

Single.just(new ConcreteResults())
                .map(new Function<ConcreteResults, IResults>() {
                    @Override
                    public IResults apply(@NonNull ConcreteResults results) throws Exception {
                        return results;
                    }
                });

Use: 采用:

@Override public Single<? extends IResults> getResults() { 
    return Single.just(new ConcreteResults()); 
}

Please remember that hieritance with genetics is a bit different. 请记住,遗传学上的嘲笑有些不同。

Although IResults is a sub type of ConcreteResults, Single of ConcreteResults is NOT a sub type of Single of IResults . 虽然IResults是ConcreteResults的子类型,但是Single ConcreteResults不是IResults的Single的子类型。 You need to use a wildcard to create a relationship between then 您需要使用通配符在

You can search for more information about it here: https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html 您可以在此处搜索有关它的更多信息: https : //docs.oracle.com/javase/tutorial/java/generics/subtyping.html

You need to create a variable before returning the value. 您需要先创建变量,然后再返回值。 The compiler will figure out, that IResult is the over-type of ConcretResult. 编译器会发现IResult是ConcretResult的过度类型。 If you return it immediately the compiler does not get it. 如果立即返回,编译器将无法获取。

@Test
void name() {
    Single<IResult> result = getResult();
}

private Single<IResult> getResult() {
    Single<IResult> just = Single.just(new Result());

    return just;
}

interface IResult {

}

class Result implements IResult {

}

For 1_7 Settings you must use: 对于1_7设置,您必须使用:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

You have to give the compiler pointers, because in 1_7 the compiler does not inference the type from definition. 您必须提供编译器指针,因为在1_7中,编译器不会从定义中推断类型。

private Single<IResult> getResult() {
    Single<IResult> just = Single.<IResult>just(new Result());

    return just;
}

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

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