RxJava 2.0转换为泛型会丢失所有类型

时间:2018-08-20 13:06:17

标签: android generics rx-java2 rx-android

我继承了一些需要概括的代码,该代码使用RxJava 2.0进行了一些处理-即从REST服务请求数据(使用Retrofit),然后使用我们自己的自定义解析器对其进行解析。

我们在同一流程中有两种略有不同的实现,我一直在试图统一它们,但运气不佳-当我开始使用通用父类型时,subscribe()会丢失所有类型并返回Objects代替。

代码如下(简化为与NDA匹配):

// MyStuff is a base class, which has two child classes inheriting
// Base processing is done in the abstract class, while type-specific
// processing is done in ParserOne and ParserTwo
public abstract class ParserBase<T extends MyStuff> {
    // This call will be specific to the actual MyStuffOne or MyStuffTwo objects, hence abstract
    public abstract Flowable<TargetModel> parse(Flowable<T> parsestuff);
    // These two calls are applied to the generic MyStuff class
    // and are shared between MyStuffOne and MyStuffTwo 
    public Flowable<Map<long,MyModel>> parseOneImpl(Flowable<T> parsestuff) { /* impl here */ }
    public Single<Map<long,MyModel>> parseTwoImpl(Flowable<T> parsestuff) { /* impl here */ }
}

public class MyStuff {
    // Some common fields here
}

public class MyStuffOne extends MyStuff {
    // Some MyStuffOne specific fields here
}

public class MyStuffTwo extends MyStuff {
    // Some MyStuffTwo specific fields here
}

public class ParserOne extends ParserBase<MyStuffOne> {
    @Override 
    public Flowable<TargetModel> parse(Flowable<MyStuffOne> parsestuff) { /* impl 1 here */ }
}

public class ParserTwo extends ParserBase<MyStuffTwo> {
    @Override 
    public Flowable<TargetModel> parse(Flowable<MyStuffTwo> parsestuff) { /* impl 2 here */ }
}

public class MyClassOne {

    protected void call() {
        ParserOne parser = new ParserOne();
        callGeneric(parser);
    }

    protected void callGeneric(ParserBase<?> parser) {
        // Common implementation here
        parser.parseOneImpl(whatever).subscribe(
            result -> { /* result ends up being Object instead of Map<Long,MyModel> */ }, 
            throwable -> { /* throwable also ends up being Object */ });
    }
}

public class MyClassTwo extends MyClassOne {
    @Override
    protected void call() {
        ParserTwo parser = new ParserTwo();
        callGeneric(parser);
    }
}

因此,尽管parseOneImpl()调用具有泛型参数,但它具有固定的返回类型-但由于某种原因,subscribe()看不到这一点,而是返回了泛型对象。我可以通过强制转换结果来解决此问题(效果很好,因为实际的运行时对象与返回类型parseOneImpl()匹配),但是我想避免这种情况。

我在这里做什么错了?

0 个答案:

没有答案