Why doesn't the return type satisfy the method signature?

131 Views Asked by At

Why doesn't the return type satisfy the method signature in the following method?

protected Observable<List<? extends Person>> getLoadPersonsObservable() {
    return StudentsProvider.getStudentsProvider().getStudents().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}

The observeOn() method returns the following:

Observable<List<Student>>

And here is the Student class:

public class Student extends Person {
    public Student(String name, String id, boolean approved) {
       super(name, id, approved);
    }
}

The error: enter image description here

For now, getStudents() is a stub method, emulating a network call:

 @Override
public Observable<List<Student>> getStudents() {

    final Observable<List<Student>> fetchStudents = Observable.create(new Observable.OnSubscribe<List<Student>>() {
        @Override
        public void call(Subscriber<? super List<Student>> subscriber) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            List <Student> stubList = new ArrayList<>();

            stubList.add(new Student("Freddie Mercury", "1", true));
            stubList.add(new Student("Jimmy Hendrix", "2", true));

            subscriber.onNext(stubList);

            subscriber.onCompleted();
        }
    });
    return fetchStudents;
}

Thanks in advance! - Mate

2

There are 2 best solutions below

0
On BEST ANSWER

First create a custom class for your Observer

private class MyObservable<T extends Person> extends Observable<List<T>>{

}

then in your activity, add this method

private MyObservable<Student> getData(){
        return new MyObservable<>();
}

This is just an example of how you can achieve what you are trying.

P.S. This might not be the final solution but it will definitely help you remove the static implementation like in your solution

0
On

Ended up passing the Person subtype reference to the parent of the caller class and changing the abstract method signature as follows:

 abstract protected Observable<List<P>> getLoadPersonsObservable();

Now the implementation of the method can look like this:

@Override
protected Observable<List<Student>> getLoadPersonsObservable() {
    return StudentsProvider.getStudentsProvider().getStudents().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}

And voila, no errors. Thank you for your help everyone!