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

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

RxJava 在 GitHub 主页上的自我介绍是 "a library for composing asynchronous and event-based programs using observable sequences for the Java VM"(一个在 Java VM 上使用可观测的序列来组成异步的、基于事件的程序的库)。


还是要实际敲上一敲印象才会深刻,才能更了明白Rx的运行过程。



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

配合Retrofit 完成数据请求

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

就是简单的网络数据获取。

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


ReactiveX/RxJava文档中文版


关于RxJava入门,我也是新手,不敢妄言,给大家分享分享网上流传的大神博客:



扔物线大大的:



给 Android 开发者的 RxJava 详解



hi大头鬼hi:


深入浅出RxJava(一:基础篇)

深入浅出RxJava ( 二:操作符 )

深入浅出RxJava ( 三--响应式的好处 )

深入浅出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'

接下来就可以写代码了。


先看下运行截图:

【Android学习】使用聚合数据的接口进行的RxAndroid学习_第1张图片【Android学习】使用聚合数据的接口进行的RxAndroid学习_第2张图片【Android学习】使用聚合数据的接口进行的RxAndroid学习_第3张图片【Android学习】使用聚合数据的接口进行的RxAndroid学习_第4张图片【Android学习】使用聚合数据的接口进行的RxAndroid学习_第5张图片


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





你可能感兴趣的:(【Android学习】使用聚合数据的接口进行的RxAndroid学习)