3

I'm writing an API client in Android using Retrofit and this sort of code gets repeated a lot:

myObservableFromRetrofit
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .doOnError(... print stack trace ...)

I'm wondering if there is a technique to avoid repeating this stuff.

I surrounding calls to retrofit functions with:

public Observable<?> commonObservable(Observable<?> observable) {
  return observable
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .doOnError(... print stack trace ...)
}

But that loses generics type information.

ktusznio
  • 3,585
  • 3
  • 22
  • 21

2 Answers2

5

Rather than wrapping your Observables, you should be using the compose() operator as detailed in this blog post. So you'd have:

<T> Transformer<T, T> applySchedulers() {  
    return observable -> observable.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnError(... print stack trace ...)
}

which you'd call like this:

myObservableFromRetrofit
    .compose(applySchedulers())

or this, if you're compiling below JDK 8:

myObservableFromRetrofit
    .compose(this.<YourType>applySchedulers())
steffandroid
  • 720
  • 9
  • 16
3

Substitute ? for T and add the missing <T>. That will allow for Type Inference to be done properly.

public <T> Observable<T> commonObservable(Observable<T> observable) {
  return observable
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .doOnError(... print stack trace ...)
}

This is an issue with Wildcard capture.

For the most part, you don't need to worry about wildcard capture, except when you see an error message that contains the phrase "capture of".

Which I'm assuming you're refering to. Here's a bit more info about it

Miguel
  • 19,793
  • 8
  • 56
  • 46