自己写的RxJava和Retrofit结合

依赖:

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

ApiService:

public interface ApiService {
    @GET
    io.reactivex.Observable get(@Url String url);
}

Util:

public class RetrofitUtil {
    private ApiService apservice;
    private static volatile RetrofitUtil retrofitutils;

    public RetrofitUtil(String baseurl) {
        if(apservice==null){
            OkHttpClient okClient = new OkHttpClient.Builder().build();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(baseurl)
                    .client(okClient)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            apservice = retrofit.create(ApiService.class);
        }
    }

    public static RetrofitUtil getInstence(String baseurl){
        if(null==retrofitutils){
            synchronized (RetrofitUtil.class){
                if(retrofitutils==null){
                    retrofitutils = new RetrofitUtil(baseurl);
                }
            }
        }
        return retrofitutils;
    }

    public void get(String url,final CallBack callback){
        io.reactivex.Observable bo = apservice.get(url);
        bo.subscribeOn(Schedulers.io())

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("Retrofit","onSubscribe");
                    }

                    @Override
                    public void onNext(Beann value) {
                        Log.e("Retrofit","请求了");
                        callback.onSuccess(value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("Retrofit","请求错了");
                    }

                    @Override
                    public void onComplete() {
                        Log.e("Retrofit","不执行其它的操作了");
                    }
                });

    }
}

你可能感兴趣的:(自己写的RxJava和Retrofit结合)