最近学习RxJava,一直在看大神的文章,分析。
还是要实际敲上一敲印象才会深刻,才能更了明白Rx的机制。
数据源是聚合数据的免费Api。
配合Retrofit 完成数据请求
例子比较简单,没事使用什么复杂的操作符。
就是简单的网络数据获取。
一些常用的操作符大家可以参考官方的文档说明:
先看下运行截图:
Api可以去聚合数据官网申请。
这几个都是GET请求,所以写法都一样:
创建接口:
- public interface WeatherApi {
- @GET("/oneBox/weather/query?")
- Observable<Weather> getWeatherInfo(@Query("cityname") String phone, @Query("key") String key);
- }
创建Retrofit:
- public static WeatherApi getWeatherApi() {
- if (weatherApi == null) {
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("http://op.juhe.cn")
- .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
- .addConverterFactory(GsonConverterFactory.create())
- .build();
- weatherApi = retrofit.create(WeatherApi.class);
- }
- return weatherApi;
- }
- RxView.clicks(btn_check).throttleFirst(3,TimeUnit.SECONDS)
- .subscribe(new Action1<Void>() {
- @Override
- public void call(Void aVoid) {
- NetWork.getWeatherApi()
- .getWeatherInfo(et_city_name.getText().toString(),API_KEY)
- .subscribeOn(Schedulers.newThread())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Action1<Weather>() {
- @Override
- public void call(Weather weather) {
- setDispaly(weather);
- }
- });
- }
- });
例子可以在git上下载参考。