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