public class RetrofitUtil { private static RetrofitUtil retrofitUtil; //创建Serveinfo引用 private static ServeInfo serveInfo; //声明私有构造方法 private RetrofitUtil(){ } /** * 先后调用的过程,只有对象给build成功之后,才能调用apiservice,这也是retrofit的几个先后的步骤 * @return */ public ServeInfo getServeInfo(){ return serveInfo; } public static class Builder{ private List<CallAdapter.Factory> factoryList = new ArrayList<>(); private List<Converter.Factory> converterList = new ArrayList<>(); private OkHttpClient okHttpClient; public Builder addCallAdapterFactory(CallAdapter.Factory factory){ factoryList.add(factory); return this; } public Builder addConverterFactory(Converter.Factory factory){ converterList.add(factory); return this; } public Builder Client(OkHttpClient okHttpClient){ this.okHttpClient = okHttpClient; return this; } public RetrofitUtil buidle(){ Retrofit.Builder builder = new Retrofit.Builder(); if(factoryList!=null&&factoryList.size()==0){ // builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create()); factoryList.add(RxJava2CallAdapterFactory.create()); } for (CallAdapter.Factory factory : factoryList) { builder.addCallAdapterFactory(factory); } if(converterList!=null&&converterList.size()==0){ converterList.add(GsonConverterFactory.create()); } for (Converter.Factory factory : converterList) { builder.addConverterFactory(factory); } //第一步创建Retrofit对象 Retrofit build = builder.client(okHttpClient).baseUrl(Constants.BASE_URL).build(); //第二部创建Serveinfo对象 serveInfo = build.create(ServeInfo.class); retrofitUtil = new RetrofitUtil(); return retrofitUtil; } } }
MainActivity
OkHttpClient okHttpClient = new OkHttpClient(); new RetrofitUtil.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .Client(okHttpClient) .buidle() .getServeInfo() .loginrxjava("71") .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<User2>() { @Override public void accept(User2 user2) throws Exception { Toast.makeText(MainActivity.this,user2.getMsg(),Toast.LENGTH_SHORT).show(); } });