使用聚合数据的接口进行的RxAndroid学习
2024-10-05 19:38:16
Demo数据源是聚合数据的免费Api,地址:https://www.juhe.cn/
配合Retrofit 完成数据请求
例子比较简单,没事使用什么复杂的操作符。
就是简单的网络数据获取。
一些常用的操作符大家可以参考官方的文档说明:
关于RxJava入门,我也是新手,不敢妄言,给大家分享分享网上流传的大神博客:
扔物线大大的:
hi大头鬼hi:
深入浅出RxJava ( 四-在Android中使用响应式编程 )
首先在项目中引入RxJava 、RxAndroid依赖:
compile 'io.reactivex:rxjava:1.0.14'
compile 'io.reactivex:rxandroid:1.1.0'
生命周期:
compile 'com.trello:rxlifecycle:0.4.0'
compile 'com.trello:rxlifecycle-components:0.4.0'
引入Retrofit依赖
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'
接下来就可以写代码了。
先看下运行截图:
Api可以去聚合数据官网申请。
这都是ListView的基本展示,所以程序步骤很简单:
一、先根据json数据,写出实体类。(用Gson插件迅速生成)
二、根据要显示的数据创建布局。
三、编写Adapter。
四、然后从网络请求并返回数据。
五、根据数据创建Adapter并绑定到listview进行显示。
这几个都是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;
}
在Activity中订阅触发代码:
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);
}
});
}
});
天气的API在代码中,可以直接使用。由于是免费接口,大家都可以申请,不过聚合数据要验证身份证。
例子可以在git上下载参考。
https://github.com/VongVia1209/RxAndroid_Demo_With_jvhe
文章来源:转载http://blog.csdn.net/castledrv/article/details/51333736
最新文章
- POJ2513-Colored Sticks
- EXP/IMP迁移案例,IMP遭遇导入表的表空间归属问题
- throw与throws的区别
- UnicodeDecodeError: &#39;utf8&#39; codec can&#39;t decode byte 0xce in position 47: invalid continuation byte
- CentOS 7下源码安装MySQL 5.7
- Go prepare statment超过mysql最大数
- HDU 5001
- cache的工作原理
- MCS-51系列和80C51系列单片机是否相同
- python使用一个集合代替列表
- IOS UIImage 模糊
- 7. Reverse Integer
- sql语句中特殊函数的用法
- Python如何调用新浪api接口的问题
- GC机制
- MyEclipse 10导入JDK1.7或1.8
- vue 事件修饰符
- 翻译 异步I/O不会创建新的线程
- PHP实现微信开发中提现功能(企业付款到用户零钱)
- c# 打印 主板信息CPU信息