【Android学习】使用聚合数据的接口进行的RxAndroid学习

前端之家收集整理的这篇文章主要介绍了【Android学习】使用聚合数据的接口进行的RxAndroid学习前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近学习RxJava,一直在看大神的文章,分析。

还是要实际敲上一敲印象才会深刻,才能更了明白Rx的机制。

数据源是聚合数据的免费Api。

配合Retrofit 完成数据请求

例子比较简单,没事使用什么复杂的操作符。

就是简单的网络数据获取

一些常用的操作符大家可以参考官方的文档说明:


ReactiveX/RxJava文档中文版




先看下运行截图:



Api可以去聚合数据官网申请。


这几个都是GET请求,所以写法都一样:

创建接口:

  1. public interface WeatherApi {
  2.  
  3. @GET("/oneBox/weather/query?")
  4. Observable<Weather> getWeatherInfo(@Query("cityname") String phone, @Query("key") String key);
  5. }


创建Retrofit:

  1. public static WeatherApi getWeatherApi() {
  2. if (weatherApi == null) {
  3. Retrofit retrofit = new Retrofit.Builder()
  4. .baseUrl("http://op.juhe.cn")
  5. .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
  6. .addConverterFactory(GsonConverterFactory.create())
  7. .build();
  8. weatherApi = retrofit.create(WeatherApi.class);
  9. }
  10. return weatherApi;
  11. }

在Activity中订阅触发代码

  1. RxView.clicks(btn_check).throttleFirst(3,TimeUnit.SECONDS)
  2. .subscribe(new Action1<Void>() {
  3. @Override
  4. public void call(Void aVoid) {
  5. NetWork.getWeatherApi()
  6. .getWeatherInfo(et_city_name.getText().toString(),API_KEY)
  7. .subscribeOn(Schedulers.newThread())
  8. .observeOn(AndroidSchedulers.mainThread())
  9. .subscribe(new Action1<Weather>() {
  10. @Override
  11. public void call(Weather weather) {
  12. setDispaly(weather);
  13. }
  14. });
  15. }
  16. });





例子可以在git上下载参考。


https://github.com/VongVia1209/RxAndroid_Demo_With_jvhe

猜你在找的设计模式相关文章