1. 程式人生 > >Retrofit+RxJava備忘

Retrofit+RxJava備忘

僅作備忘。

 

//配置retrofit2.0
    compile 'com.squareup.retrofit2:retrofit:+'
    compile 'com.squareup.retrofit2:converter-gson:+'
 
//rxjava
compile 'com.squareup.retrofit2:adapter-rxjava2:+'
compile 'io.reactivex.rxjava2:rxjava:+'
compile 'io.reactivex.rxjava2:rxandroid:+'

retroft + rxjava 工具類

public class RetrofitManager {

    private final Retrofit mRetrofit;
    private static final String BASE_URL = "baseURl,以/結尾";
    private static final class SINGLE_INSTENCE {
        private static final RetrofitManager INSTENCE = new RetrofitManager();
    }


    public static RetrofitManager getInstence() {
        return SINGLE_INSTENCE.INSTENCE;
    }

    public RetrofitManager() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(buildOkHttpClient())
                .build();
    }

    private OkHttpClient buildOkHttpClient(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);

       return new OkHttpClient.Builder()
               .addInterceptor(interceptor)
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5,TimeUnit.SECONDS)
                .readTimeout(5,TimeUnit.SECONDS)
                .build();
    }

    public <T> T create(Class<T> tClass) {
        return mRetrofit.create(tClass);
    }
}

 M層呼叫,


public Observable<LoginBean(登入的bean類)> login(String mobile, String password){
        ILoginBean iLoginBean = RetrofitManager.getInstence().create(ILoginBean.class);//拼接的Bean類
        return iLoginBean.login(mobile,password);
    }

 p層傳值後,分配工作,ui執行緒:

 model.reg(mobile,password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RegBean>() {
                    @Override
                    public void accept(RegBean regBean) throws Exception {
                        Log.d(TAG, "accept: "+ regBean.getMsg());
                        if (iView != null){
                            if (regBean != null){
                                iView.onSuccess(regBean);
                            }

                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (iView != null){
                            String message = throwable.getMessage();
                            iView.onFaild(message);
                        }
                    }
                });

 

介面bean類     

@GET("user/reg")
    Observable<RegBean> reg(@Query("mobile") String mobile, @Query("password") String password);

導包非常容易不在意,

io.reactivex.Observable包下