Eve Eve - 6 months ago 31
Android Question

Rxjava static generic utility method with transformer

Recently I saw an

RxJava
article explaining
Transformers
and highlighting how they could be used to reuse
Schedulers
. I tried to use this and inside the same class, this method works fine:

<T>Observable.Transformer<T, T> applySchedulers() {
return new Observable.Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> observable) {
return observable
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}


I want to move this into a helper class with a static method so I can use it in my whole
Android
app. But when I try to use the method of this class

public class RxFunctions {

public static <T>Observable.Transformer<T, T> applySchedulers() {
return new Observable.Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> observable) {
return observable
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
}


inside another class

public void requestLoginState() {
restClient.requestLoginState()
.compose(RxFunctions.applySchedulers())
.subscribe(new TimberErrorSubscriber<LoginStateResponse>() {
@Override
public void onCompleted() {
}
...


it will no longer recognise my
Subscriber
, error:
Cannot resolve method 'subscribe(anonymous com.example.util.rx.TimberErrorSubscriber<com.example.network.retrofit.response.login.LoginStateResponse>)'


I'm using
Java8
without
Retrolambda
.
Changing the compose line to

.compose(this.<LoginStateResponse> RxFunctions.applySchedulers())


results in an error for the LoginState type saying
Reference parameters are not allowed here


I'm fairly new to
RxJava
and grateful for any advice.

Answer

Edit: now Android does support java 8

You say you are using Java8 on android, but android does not support Java8 without plugins like retrolambda, so I'll asume that you are actually compiling with Java6 (since Java7 only works for KitKat and above).

In that scenario, you might need to make explicit the parametric type of your applySchedulers. I believe you tried to do that when you wrote this.<LoginStateResponse>, but that would only work if your generic method is inside your current class.

In your case what you actually need is to specify the type on the static method call:

.compose(RxFunctions.<LoginStateResponse>applySchedulers())