如何更好地使用RxJava + Retrofit?

时间:2016-09-06 03:05:38

标签: java android

我知道创建RxJava是为了使代码像流一样。但是,在我的代码中,实际上我必须频繁地发出HTTP请求,并且每次使用RxJava + Retrofit进行网络工作时都会发现它不那么优雅我必须多次编写相同的代码。 所以我把下面的代码包围起来

public APIHelper(String url){
    retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .baseUrl(url)
            .client(setheader())
            .build();
}

private static OkHttpClient setheader() {

    OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request()
                            .newBuilder()
                            .addHeader("UserID", "")
                            .addHeader("hec-username", USERNAME)
                            .addHeader(AUTHENTICATION_KEY, TOKEN)
                            .build();
                    return chain.proceed(request);
                }
            }).build();
    return  httpClient;
}

public Retrofit getRetrofit(){
    if(retrofit!=null)
        return retrofit;
    else
        return null;
}

public void excuteRxJava(Observable<T> observable){
                observable
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<T>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(T t) {
                        doNext(t);
                    }
                });
}

public abstract void doNext(T t);

public abstract List<S> doInFrom(T t);

public abstract void doAction(T t);

其他一些抽象方法用于在onDoNext,flatMap中执行某些操作。而我想问的是,这种封装是否适合Rx的概念?

1 个答案:

答案 0 :(得分:-1)

制作一些utils类。

public class RetrofitUtils {
public static final String Tag = RetrofitUtils.class.getSimpleName();
public static <T> T getInstance(final Class<T> service)
{
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constant.SERVER_URL)//做成静态变量
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
    T t = retrofit.create(service);
    return t;
}

}

                final UserInterface instance = RetrofitUtils.getInstance(UserInterface.class);
                Observable<JsonElement> register = instance.resetPassword(Des3.encodeAndUrl(etUsername.getText().toString().trim()), Des3.encodeAndUrl(etPassword.getText().toString().trim()), etVcode.getText().toString().trim());
                RetrofitFlow.getData(register).subscribe(new DefaultSubscriber<JsonElement>() {
                    @Override
                    public void onNext(JsonElement jsonElement) {
                        LogUtil.i(jsonElement.toString());
                        RxBus.getDefault().post(new LoginJumpBean(null, LoginJumpBean.AIM_FINISH_ACTIVITY));
                    }
                });

public abstract class DefaultSubscriber<T> extends Subscriber<T> {
    public static final String Tag = DefaultSubscriber.class.getSimpleName();

    @Override
    public void onCompleted() {
        LogUtil.i("完成");
    }

    @Override
    public void onError(Throwable e) {
        LogUtil.i("发生错误:"+e.getMessage());
    }


}

使用rxjava过滤器结果。