How can I avoid repeating common observable configuration?

随声附和 提交于 2020-01-01 18:19:31

问题


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.


回答1:


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




回答2:


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())


来源:https://stackoverflow.com/questions/25575801/how-can-i-avoid-repeating-common-observable-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!