retrofit和RxJava结合
Posted ocean123123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了retrofit和RxJava结合相关的知识,希望对你有一定的参考价值。
public class MainActivity extends AppCompatActivity @SuppressLint("CheckResult") protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ApiClient.retrofit().create(ApiStores.class).loadDataByRetrofitRxJava("101220602") .subscribeOn(Schedulers.io()) .observeOn(androidSchedulers.mainThread()) .subscribe(new Observer<MainModel>() @Override public void onSubscribe(Disposable d) Log.w("输出:", "连接" ); @Override public void onNext(MainModel mainModel) Log.w("输出:", "" + mainModel.getWeatherinfo().getCity()); Log.d("输出:", "observer thread is : " + Thread.currentThread().getName()); @Override public void onError(Throwable e) Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show(); @Override public void onComplete() Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show(); ); public interface ApiStores //baseUrl String API_SERVER_URL = "http://www.weather.com.cn/"; //加载天气 @GET("adat/sk/cityId.html") Observable<MainModel> loadDataByRetrofitRxJava(@Path("cityId") String cityId);
主方法
public class ApiClient public static Retrofit mRetrofit; public static Retrofit retrofit() if (mRetrofit == null) OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.readTimeout(5, TimeUnit.SECONDS); builder.connectTimeout(5, TimeUnit.SECONDS); if (BuildConfig.DEBUG) // Log信息拦截器 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); //设置 Debug Log 模式 builder.addInterceptor(loggingInterceptor); OkHttpClient okHttpClient = builder.build(); mRetrofit = new Retrofit.Builder() .baseUrl(MainActivity.ApiStores.API_SERVER_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build(); return mRetrofit;
新建类
public class MainModel public static WeatherinfoBean getWeatherinfo() return new WeatherinfoBean(); public static class WeatherinfoBean private String city; public String getCity() return city; public void setCity(String city) this.city = city;
implementation ‘io.reactivex.rxjava2:rxjava:2.2.9‘ implementation ‘io.reactivex.rxjava2:rxandroid:2.1.1‘ //retrofit implementation ‘com.squareup.retrofit2:retrofit:2.6.0‘ //Gson converter implementation ‘com.squareup.retrofit2:converter-gson:2.6.0‘ //RxJava2 Adapter implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0" //okhttp implementation ‘com.squareup.okhttp3:okhttp:3.12.0‘ implementation ‘com.squareup.okhttp3:logging-interceptor:3.9.1‘
直接把依赖复制到build.gride然后同步
以上是关于retrofit和RxJava结合的主要内容,如果未能解决你的问题,请参考以下文章
Android RxJava/RxAndroid结合Retrofit使用