使用RxJava+Retrofit完成同步连续请求

首先声明一下,这是本人的学习Rxjava和Retrofit的第一篇博客,也是我第一次写博客,内容中可能会有错误的地方或者我理解错误的地方,请大家多理解,都是这么过来的嘛,如果有错误的地方非常欢迎大家指正,我会及时修改以免误导他人。

使用场景

连续请求在很多App中都经常会被使用,例如通过定位获得当前定位城市的天气预报,我们首先要通过Android为我们提供的Api调用GPS获得我们当前的经纬度,然后将经纬度转换成具体的城市名称,再将城市名称传入获取天气预报的请求中。

如果要实现这样一个需求,在代码结构上可能会是很乱的,我们可能会陷入无尽的回调地狱中,例如这样:

使用RxJava+Retrofit完成同步连续请求_第1张图片
快的打车

这样的结构无论对于开发人员还是维护人员都非常容易一脸懵逼,为了解决这个问题,我们可以通过引入Rxjava+Retrofit,使用链式的结构,让整个代码块更易读,也为了让你离职后接手你的项目的人少骂你几句。

动手试一下

前期准备

  • 经纬度转为城市地址Api:由于Google Maps提供的Api在国内无法使用(也可能有更好的方法请指教),我找到了
    http://api.map.baidu.com/geocoder?location=纬度,经度&output=输出格式类型&key=用户密钥这个Api来代替,注意这个Api要提前申请key,本文将提供一个key:6eea93095ae93db2c77be9ac910ff311

  • 天气预报Api:这里我使用的是心知天气在百度Api服务中提供的接口,其中我使用了天气实况这一服务,具体的接口Url为http://apis.baidu.com/thinkpage/weather_api_full/currentweather,注意这里同样要申请key,此处需要各位自行申请了。

  • Rxjava+Retrofit:通过Gradle导入即可

    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.jakewharton:butterknife:7.0.1'

可以开始了

首先我们要准备好天气服务和位置服务返回的实体类,这个实体类就需要麻烦大家自行去请求一下了,这里推荐一个Chrome的小插件Postman(需要翻墙)这个工具可以帮助你进行网页调试或发送http请求。自动生成实体类应该不用多说了GsonFormat即可搞定。

现在我们有了实体类,接下来我们就要通过Retrofit为每个请求创建相应的Service了:

  • 定位服务:
public interface LocationService {
    @GET("geocoder")
    Observable getLoation(
    @Query("location") String location, 
    @Query("output") String output,
    @Query("key") String key
    );
}
  • 天气服务 请将代码中的***替换为您申请的apikey
public interface WeatherService {
    @Headers({"apikey:*********"})
    @GET("currentweather")
    Observable getWeather(@Query("location") String city);
}

接下来我们为每个请求实例化相应的Retrofit对象,并加入Rxjava的支持:

public static final String WEATHER_URL = "http://apis.baidu.com/thinkpage/weather_api/";
public static final String LOCATION_URL ="http://api.map.baidu.com/";

Retrofit mRetrofitWeather;
Retrofit mRetrofitLocation;
WeatherService mWeatherService;
LocationService mLocationService;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRetrofitWeather = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(WEATHER_URL)
                .build();
        mWeatherService = mRetrofitWeather.create(WeatherService.class);

        mRetrofitLocation = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(LOCATION_URL)
                .build();
        mLocationService = mRetrofitLocation.create(LocationService.class);
  }

下面就是我们的重点了,我们要使用Rxjava为我们提供的十分丰富的操作符来完成这个连续的请求。声明一下我是在点击事件中完成的请求

public void getWeather(){
     mLocationService.getLoation("31.407452,119.490523", "json", "6eea93095ae93db2c77be9ac910ff311")
     .flatMap(new Func1>() {
           @Override
           public Observable call(LocationEntity locationEntity) {
               return mWeatherService.getWeather(locationEntity.getResult().getAddressComponent().getCity());
           }
     }).map(new Func1() {
           @Override
           public String call(WeatherEntity weatherEntity) {
                String text = weatherEntity.getResults().get(0).getLocation().getName() + ":" + weatherEntity.getResults().get(0).getNow().getText()+ " 温度:" + weatherEntity.getResults().get(0).getNow().getTemperature() + "";
                return text;
          }
     }).subscribeOn(Schedulers.io())
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(new Subscriber() {
           @Override
           public void onCompleted() {
                 Log.d(TAG, "onCompleted: " + "完成数据获取");
           }

           @Override
           public void onError(Throwable e) {
                 tv.setText(e.toString());
            }


            @Override
            public void onNext(String s) {
                  tv.setText(s);
                  Log.d(TAG,"当前天气为:"+s)
             }   
      });
}

首先我们通过系统的Api拿到我们目前所在位置的经纬度信息,这里我就直接随意写了一个,接下来我们就要开始传入接口所需要的参数进行请求了,第一步我们先要通过经纬度获得我们所在的城市位置,这里我使用了Map和FlatMap这两个操作符。

Map
transform the items emitted by an Observable by applying a function to each item

FlatMap
transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable

从文档中我们可以看出,FlatMap可以将Observable对象发射到一个Observables对象中,然后排列为一个Observable对象,通过该操作符,我们可以将得到的位置信息传入天气服务的Api中,将或得到的天气实体发射到Observables中,之后我们再通过map操作符将天气的Observable对象通过处理,得到我们所需要的具体信息,即文中的text,之后我们订阅这个事件,在onNext方法中取得我们所需的信息。

这样的链式结构相对于文中开头的回调地狱来说,虽说学习成本较高,但是一旦学会使用Rxjava,好处确实是非常多的,最后谢谢大家的阅读。

项目地址

Github: https://github.com/icetea0822/Rxjava-Retrofit

这个项目本是我学习Rxjava和Retrofit练手用的,所以里面也一些不相关的东西,而且在学习时谷歌刚刚在北京开完开发者大会,试了试Firebase和Google ads请见谅,大家请无视下面的广告。

你可能感兴趣的:(使用RxJava+Retrofit完成同步连续请求)