MBH
MBH

Reputation: 16619

Static Generic Method in Class - Java

I am using RxJava on Android for doing some stuff,

I always do the same stuff on the observable before using it like this :

Observable<AnyObject> observable = getSomeObservable();
// The next 2 lines are the lines that i always add them to any Observable
observable.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.computation());

Hence the Observable is generic and can be any object, if i want to add those two lines on it and return it in a Statis method, i need to make the method also Generic

What i was trying to do is to pass the observable by parameter, add set it up and return it back as following:

public class UtilsObservable<T> {

    public static Observable<T> setupObservable(Observable<T> observable) {
        return observable.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.computation());
}

I got a compile error here says:

UtilsObservable.this cannot be referenced from a static context

pic

My Question is :

So can this be done in anyway ? Generic method takes generic object modify it and return the same type ?

Upvotes: 0

Views: 305

Answers (2)

Mikhail Spitsin
Mikhail Spitsin

Reputation: 2608

First of all don't break the chain, please.

And second of all follow resueman answer:

public static <T> Observable<T> setupObservable(Observable<T> observable) {
    return observable.observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.computation());

Upvotes: 2

resueman
resueman

Reputation: 10613

The issue is because the generic type T is linked to a specific instance of the UtilsObservable class, but in a static context you don't have an instance to reference. You need to make the method generic, independent of the class's generic type.

public class UtilsObservable<T> {

    public static <T> Observable<T> setupObservable(Observable<T> observable) {
        return observable.observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.computation());
}

Notice the additional <T> before the method type. That gives the method itself a generic type, which is no longer connected to an instance of the class.

Upvotes: 5

Related Questions