加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 02:14:25 所属栏目:百科 来源:网络整理
导读:最近学习RxJava,一直在看大神的文章,分析。 还是要实际敲上一敲印象才会深刻,才能更了明白Rx的机制。 数据源是聚合数据的免费Api。 配合Retrofit 完成数据请求 例子比较简单,没事使用什么复杂的操作符。 就是简单的网络数据获

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

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

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

配合Retrofit 完成数据请求

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

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

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


ReactiveX/RxJava文档中文版




先看下运行截图:



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;
}

在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);
                            }
                        });
            }
        });





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


https://github.com/VongVia1209/RxAndroid_Demo_With_jvhe

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读