標籤:
Demo資料來源是彙總資料的免費Api,地址:https://www.juhe.cn/
配合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‘
接下來就可以寫代碼了。
先看下運行:
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
使用彙總資料的介面進行的RxAndroid學習