Retrofit+Rxjava的一个简单使用(无封装)

1. 天气预报Demo来源及参考

https://www.jianshu.com/p/34187b90fe57
https://www.jianshu.com/p/06a35a0f34d2

2. WeatherEntity

  • generate→GsonFormat工具跨界生成Entity类
  • 重写toString()方法
public class WeatherEntity {
    private List HeWeather6;
    public List getHeWeather6() { return HeWeather6; }
    public void setHeWeather6(List HeWeather6) { this.HeWeather6 = HeWeather6; }
    public static class HeWeather6Bean {...}
     @Override
    public String toString() {...}
}

3. WeatherService

  • 根据API新建接口类
  • 方法返回 Observable
public interface WeatherService {
    @GET("s6/weather/now")
    Observable getWeather(@Query("key") String key,@Query("location") String location);
}

4. Okhttp初始化

  • 设置超时时间5s
  • ???为什么要有OKHttp
    Retrofit本质是一个整合工具,OkHttp是他的一个网络框架的选择之一,用来对网络请求进行约束,设置拦截器,缓存,超时时间等
okhttp3.OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);

5. Retrofit初始化

  • client()
  • baseUrl()
  • addConverterFactory() 添加转换器,将response转换成我们想要的T
  • addCallAdapterFactory() 对回调方式做封装,将Call接口转换成RxJava的接口
  • retrofit.create(WeatherService.class) 实例化接口
Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl("https://free-api.heweather.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        WeatherService weatherService = retrofit.create(WeatherService.class);

6. Rxjava处理数据

  • getWeather() 发起request
  • observrOn() 指定subscribe() 线程
  • subscribe(new Observer(){}) 相当于.enqueue(callback),用于处理response
weatherService.getWeather("0ab2e140e73441de9e726a044c266d16",city)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer() {
                        @Override
                        public void onSubscribe(Disposable d) {}
                        @Override
                        public void onNext(WeatherEntity weatherEntity) {
                            weatherEntities.add(weatherEntity);
                        }
                        @Override
                        public void onError(Throwable e) {
                            view.dateError(e);
                        }
                        @Override
                        public void onComplete() {
                            view.setData(weatherEntities);
                        }
                    });

你可能感兴趣的:(Retrofit+Rxjava的一个简单使用(无封装))