Android中RxJava+Retrofit2.0+MVP模式的整合
生活随笔
收集整理的這篇文章主要介紹了
Android中RxJava+Retrofit2.0+MVP模式的整合
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
版權聲明:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/u010046908/article/details/50781360
轉載請標明出處:http://blog.csdn.net/u010046908/article/details/50781360 本文出自:【李東的博客】
MVP的工作原理
以上是MVP的工作原理圖。其中大家注意的Presenter操作View和Mode都是通過接口來實現直接的調用。
MVP的工作流程
- Presenter負責邏輯的處理,
- Model提供數據,
- View負責顯示。
作為一種新的模式,在MVP中View并不直接使用Model,它們之間的通信是通過Presenter來進行的,所有的交互都發生在Presenter內部,而在MVC中View會從直接Model中讀取數據而不是通過 Controller。
RxJava和Retrofit2.0使用
這二者的使用我就不羅嗦了,github中后好多demo,大家自己看。
MVP、RxJava和Reterofit2.0三者的整合現在開始講解
首先說一下本項目的結構
- api包主要存放網絡請求接口
- bean包中存放實體類
- model包中存放處理數據
- pesenter包中存放主導器
- view包中存放界面處理
view的代碼:
/** *WeatherView 用于處理界面顯示 */ public interface WeatherView {void showProgress();void hideProgress();void loadWeather(WeatherData weatherData); }package com.lidong.demo.android_rapid_development_of_library.mvp;import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.widget.TextView; import android.widget.Toast;import com.lidong.android_ibrary.LoadingUIHelper; import com.lidong.demo.android_rapid_development_of_library.R; import com.lidong.demo.android_rapid_development_of_library.mvp.bean.WeatherData; import com.lidong.demo.android_rapid_development_of_library.mvp.presenter.WeatherPresenter; import com.lidong.demo.android_rapid_development_of_library.mvp.presenter.WeatherPresenterImp; import com.lidong.demo.android_rapid_development_of_library.mvp.view.WeatherView;import butterknife.Bind; import butterknife.ButterKnife; /** *展示天氣詳情 */ public class WeatherActivity extends AppCompatActivity implements WeatherView {@Bind(R.id.toolbar)Toolbar toolbar;@Bind(R.id.textView1)TextView textView1;@Bind(R.id.textView2)TextView textView2;@Bind(R.id.textView3)TextView textView3;@Bind(R.id.textView4)TextView textView4;@Bind(R.id.textView5)TextView textView5;@Bind(R.id.textView6)TextView textView6;@Bind(R.id.textView7)TextView textView7;@Bind(R.id.textView8)TextView textView8;@Bind(R.id.textView9)TextView textView9;private WeatherPresenter mWeatherPresenter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_weather);ButterKnife.bind(this);setSupportActionBar(toolbar);mWeatherPresenter = new WeatherPresenterImp(this);mWeatherPresenter.getWeatherData("2", "蘇州");}@Overridepublic void showProgress() {LoadingUIHelper.showDialogForLoading(this,"獲取數據",false);}@Overridepublic void hideProgress() {LoadingUIHelper.hideDialogForLoading();Toast.makeText(this,"服務器異常",Toast.LENGTH_SHORT).show();mWeatherPresenter.onUnsubscribe();}@Overridepublic void loadWeather(WeatherData weatherData) {Log.d("weatherData", "weatherData==" + weatherData.toString());textView1.setText("城市:"+weatherData.getResult().getToday().getCity());textView2.setText("日期:"+weatherData.getResult().getToday().getWeek());textView3.setText("今日溫度:"+weatherData.getResult().getToday().getTemperature());textView4.setText("天氣標識:" +WeatherIDUtils.transfer(weatherData.getResult().getToday().getWeather_id().getFa()));textView5.setText("穿衣指數:" + weatherData.getResult().getToday().getDressing_advice());textView6.setText("干燥指數:"+weatherData.getResult().getToday().getDressing_index());textView7.setText("紫外線強度:"+weatherData.getResult().getToday().getUv_index());textView8.setText("穿衣建議:"+weatherData.getResult().getToday().getDressing_advice());textView9.setText("旅游指數:"+weatherData.getResult().getToday().getTravel_index());} }@Overrideprotected void onDestroy() {super.onDestroy();//取消注冊mWeatherPresenter.onUnsubscribe();}model層中的代碼
/**** Created by lidong on 2016/3/2.*/ public interface WeatherModel {/*** 獲取天氣信息* @param format* @param city*/Subscription getWeatherData(String format, String city);}/*** Created by lidong on 2016/3/2.*/ public class WeatherModelImp implements WeatherModel {private WeatherOnListener mWeatherOnListener;public WeatherModelImp(WeatherOnListener mWeatherOnListener) {this.mWeatherOnListener = mWeatherOnListener;}@Overridepublic void getWeatherData(String format,String city) { @Overridepublic Subscription getWeatherData(String format,String city) {Observable<WeatherData> request = com.lidong.demo.mvp_dagger2.api.ApiManager.getWeatherData(format, city).cache();Subscription sub = request.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<WeatherData>() {@Overridepublic void call(WeatherData weatherData) {mWeatherOnListener.onSuccess(weatherData);}}, new Action1<Throwable>() {@Overridepublic void call(Throwable throwable) {mWeatherOnListener.onFailure(throwable);}});return sub;}/***回調接口*/public interface WeatherOnListener{void onSuccess(WeatherData s);void onFailure(Throwable e);} }presenter層中的代碼:
/*** Created by lidong on 16/9/10.*/ public class BasePresenter {protected CompositeSubscription mCompositeSubscription;//RXjava取消注冊,以避免內存泄露public void onUnsubscribe() {if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {mCompositeSubscription.unsubscribe();}}//RXjava注冊public void addSubscription(Subscription subscriber) {if (mCompositeSubscription == null) {mCompositeSubscription = new CompositeSubscription();}mCompositeSubscription.add(subscriber);} }/*** Created by lidong on 2016/3/2.*/ public abstract class WeatherPresenter extends BasePresenter{/*** 獲取天氣信息* @param format* @param city*/public abstract void getWeatherData(String format, String city); }package com.lidong.demo.mvp.presenter;import android.util.Log;import com.lidong.demo.mvp.bean.WeatherData; import com.lidong.demo.mvp.model.WeatherModel; import com.lidong.demo.mvp.model.WeatherModelImp; import com.lidong.demo.mvp.view.WeatherView;/*** Created by lidong on 2016/3/2.*/ public class WeatherPresenterImp extends WeatherPresenter implements WeatherModelImp.WeatherOnListener{/*** WeatherModel和WeatherView都是通過接口來實現,這就Java設計原則中依賴倒置原則使用*/private WeatherModel mWeatherModel;private WeatherView mWeatherView;public WeatherPresenterImp( WeatherView mWeatherView) {this.mWeatherModel = new WeatherModelImp(this);this.mWeatherView = mWeatherView;}@Overridepublic void getWeatherData(String format, String city) {mWeatherView.showProgress();addSubscription(mWeatherModel.getWeatherData(format,city));}@Overridepublic void onSuccess(WeatherData s) {mWeatherView.loadWeather(s);mWeatherView.hideProgress();Log.d("-------", "onSuccess() called with: " + "s = [" + s.toString() + "]");}@Overridepublic void onFailure(Throwable e) {mWeatherView.hideProgress();Log.d("-------", "onFailure" + e.getMessage());} }api層的代碼
package com.lidong.demo.android_rapid_development_of_library.mvp.api;import com.lidong.demo.android_rapid_development_of_library.mvp.bean.WeatherData;import retrofit.GsonConverterFactory; import retrofit.Retrofit; import retrofit.RxJavaCallAdapterFactory; import rx.Observable;/*** Created by lidong on 2016/3/2.*/ public class ApiManager {private static final String ENDPOINT = "http://v.juhe.cn";private static final Retrofit sRetrofit = new Retrofit .Builder().baseUrl(ENDPOINT).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 使用RxJava作為回調適配器.build();private static final ApiManagerService apiManager = sRetrofit.create(ApiManagerService.class);/*** 獲取天氣數據* @param city* @return*/public static Observable<WeatherData> getWeatherData(String format, String city) {return apiManager.getWeatherData(format,city,"ad1d20bebafe0668502c8eea5ddd0333");}}package com.lidong.demo.android_rapid_development_of_library.mvp.api;import com.lidong.demo.android_rapid_development_of_library.mvp.bean.WeatherData;import retrofit.http.GET; import retrofit.http.Query; import rx.Observable;/*** @className:ApiManagerService* Created by lidong on 2016/3/2.*/ public interface ApiManagerService { //http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=ad1d20bebafe0668502c8eea5ddd0333/*** 獲取數據* @param cityname* @param key* @return*/@GET("/weather/index")Observable<WeatherData> getWeatherData(@Query("format") String format,@Query("cityname") String cityname,@Query("key") String key);}bean層的代碼
package com.lidong.demo.android_rapid_development_of_library.mvp.bean;import java.util.List;/*** Created by Administrator on 2015/12/21.*/ public class WeatherData {/*** resultcode : 200* reason : successed!* result : {"sk":{"temp":"18","wind_direction":"東南風","wind_strength":"2級","humidity":"41%","time":"14:32"},"today":{"temperature":"8℃~17℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東南風3-4 級","week":"星期三","city":"蘇州","date_y":"2016年03月02日","dressing_index":"較冷","dressing_advice":"建議著厚外套加毛衣等服裝。年老體弱者宜著大衣、呢外套加羊毛衫。","uv_index":"弱","comfort_index":"","wash_index":"較適宜","travel_index":"較適宜","exercise_index":"較適宜","drying_index":""},"future":[{"temperature":"8℃~17℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東南風3-4 級","week":"星期三","date":"20160302"},{"temperature":"11℃~21℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東南風3-4 級","week":"星期四","date":"20160303"},{"temperature":"12℃~19℃","weather":"多云轉陰","weather_id":{"fa":"01","fb":"02"},"wind":"東南風3-4 級","week":"星期五","date":"20160304"},{"temperature":"10℃~19℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東北風3-4 級","week":"星期六","date":"20160305"},{"temperature":"11℃~20℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東南風3-4 級","week":"星期日","date":"20160306"},{"temperature":"10℃~19℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東北風3-4 級","week":"星期一","date":"20160307"},{"temperature":"12℃~19℃","weather":"多云轉陰","weather_id":{"fa":"01","fb":"02"},"wind":"東南風3-4 級","week":"星期二","date":"20160308"}]}* error_code : 0*/private String resultcode;private String reason;/*** sk : {"temp":"18","wind_direction":"東南風","wind_strength":"2級","humidity":"41%","time":"14:32"}* today : {"temperature":"8℃~17℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東南風3-4 級","week":"星期三","city":"蘇州","date_y":"2016年03月02日","dressing_index":"較冷","dressing_advice":"建議著厚外套加毛衣等服裝。年老體弱者宜著大衣、呢外套加羊毛衫。","uv_index":"弱","comfort_index":"","wash_index":"較適宜","travel_index":"較適宜","exercise_index":"較適宜","drying_index":""}* future : [{"temperature":"8℃~17℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東南風3-4 級","week":"星期三","date":"20160302"},{"temperature":"11℃~21℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東南風3-4 級","week":"星期四","date":"20160303"},{"temperature":"12℃~19℃","weather":"多云轉陰","weather_id":{"fa":"01","fb":"02"},"wind":"東南風3-4 級","week":"星期五","date":"20160304"},{"temperature":"10℃~19℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東北風3-4 級","week":"星期六","date":"20160305"},{"temperature":"11℃~20℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東南風3-4 級","week":"星期日","date":"20160306"},{"temperature":"10℃~19℃","weather":"多云","weather_id":{"fa":"01","fb":"01"},"wind":"東北風3-4 級","week":"星期一","date":"20160307"},{"temperature":"12℃~19℃","weather":"多云轉陰","weather_id":{"fa":"01","fb":"02"},"wind":"東南風3-4 級","week":"星期二","date":"20160308"}]*/private ResultEntity result;private int error_code;public void setResultcode(String resultcode) {this.resultcode = resultcode;}public void setReason(String reason) {this.reason = reason;}public void setResult(ResultEntity result) {this.result = result;}public void setError_code(int error_code) {this.error_code = error_code;}public String getResultcode() {return resultcode;}public String getReason() {return reason;}public ResultEntity getResult() {return result;}public int getError_code() {return error_code;}public static class ResultEntity {/*** temp : 18* wind_direction : 東南風* wind_strength : 2級* humidity : 41%* time : 14:32*/private SkEntity sk;/*** temperature : 8℃~17℃* weather : 多云* weather_id : {"fa":"01","fb":"01"}* wind : 東南風3-4 級* week : 星期三* city : 蘇州* date_y : 2016年03月02日* dressing_index : 較冷* dressing_advice : 建議著厚外套加毛衣等服裝。年老體弱者宜著大衣、呢外套加羊毛衫。* uv_index : 弱* comfort_index :* wash_index : 較適宜* travel_index : 較適宜* exercise_index : 較適宜* drying_index :*/private TodayEntity today;/*** temperature : 8℃~17℃* weather : 多云* weather_id : {"fa":"01","fb":"01"}* wind : 東南風3-4 級* week : 星期三* date : 20160302*/private List<FutureEntity> future;public void setSk(SkEntity sk) {this.sk = sk;}public void setToday(TodayEntity today) {this.today = today;}public void setFuture(List<FutureEntity> future) {this.future = future;}public SkEntity getSk() {return sk;}public TodayEntity getToday() {return today;}public List<FutureEntity> getFuture() {return future;}public static class SkEntity {private String temp;private String wind_direction;private String wind_strength;private String humidity;private String time;public void setTemp(String temp) {this.temp = temp;}public void setWind_direction(String wind_direction) {this.wind_direction = wind_direction;}public void setWind_strength(String wind_strength) {this.wind_strength = wind_strength;}public void setHumidity(String humidity) {this.humidity = humidity;}public void setTime(String time) {this.time = time;}public String getTemp() {return temp;}public String getWind_direction() {return wind_direction;}public String getWind_strength() {return wind_strength;}public String getHumidity() {return humidity;}public String getTime() {return time;}@Overridepublic String toString() {return "SkEntity{" +"temp='" + temp + '\'' +", wind_direction='" + wind_direction + '\'' +", wind_strength='" + wind_strength + '\'' +", humidity='" + humidity + '\'' +", time='" + time + '\'' +'}';}}public static class TodayEntity {@Overridepublic String toString() {return "TodayEntity{" +"temperature='" + temperature + '\'' +", weather='" + weather + '\'' +", weather_id=" + weather_id +", wind='" + wind + '\'' +", week='" + week + '\'' +", city='" + city + '\'' +", date_y='" + date_y + '\'' +", dressing_index='" + dressing_index + '\'' +", dressing_advice='" + dressing_advice + '\'' +", uv_index='" + uv_index + '\'' +", comfort_index='" + comfort_index + '\'' +", wash_index='" + wash_index + '\'' +", travel_index='" + travel_index + '\'' +", exercise_index='" + exercise_index + '\'' +", drying_index='" + drying_index + '\'' +'}';}private String temperature;private String weather;/*** fa : 01* fb : 01*/private WeatherIdEntity weather_id;private String wind;private String week;private String city;private String date_y;private String dressing_index;private String dressing_advice;private String uv_index;private String comfort_index;private String wash_index;private String travel_index;private String exercise_index;private String drying_index;public void setTemperature(String temperature) {this.temperature = temperature;}public void setWeather(String weather) {this.weather = weather;}public void setWeather_id(WeatherIdEntity weather_id) {this.weather_id = weather_id;}public void setWind(String wind) {this.wind = wind;}public void setWeek(String week) {this.week = week;}public void setCity(String city) {this.city = city;}public void setDate_y(String date_y) {this.date_y = date_y;}public void setDressing_index(String dressing_index) {this.dressing_index = dressing_index;}public void setDressing_advice(String dressing_advice) {this.dressing_advice = dressing_advice;}public void setUv_index(String uv_index) {this.uv_index = uv_index;}public void setComfort_index(String comfort_index) {this.comfort_index = comfort_index;}public void setWash_index(String wash_index) {this.wash_index = wash_index;}public void setTravel_index(String travel_index) {this.travel_index = travel_index;}public void setExercise_index(String exercise_index) {this.exercise_index = exercise_index;}public void setDrying_index(String drying_index) {this.drying_index = drying_index;}public String getTemperature() {return temperature;}public String getWeather() {return weather;}public WeatherIdEntity getWeather_id() {return weather_id;}public String getWind() {return wind;}public String getWeek() {return week;}public String getCity() {return city;}public String getDate_y() {return date_y;}public String getDressing_index() {return dressing_index;}public String getDressing_advice() {return dressing_advice;}public String getUv_index() {return uv_index;}public String getComfort_index() {return comfort_index;}public String getWash_index() {return wash_index;}public String getTravel_index() {return travel_index;}public String getExercise_index() {return exercise_index;}public String getDrying_index() {return drying_index;}public static class WeatherIdEntity {private String fa;private String fb;public void setFa(String fa) {this.fa = fa;}public void setFb(String fb) {this.fb = fb;}public String getFa() {return fa;}public String getFb() {return fb;}}}public static class FutureEntity {private String temperature;private String weather;/*** fa : 01* fb : 01*/private WeatherIdEntity weather_id;private String wind;private String week;private String date;public void setTemperature(String temperature) {this.temperature = temperature;}public void setWeather(String weather) {this.weather = weather;}public void setWeather_id(WeatherIdEntity weather_id) {this.weather_id = weather_id;}public void setWind(String wind) {this.wind = wind;}public void setWeek(String week) {this.week = week;}public void setDate(String date) {this.date = date;}public String getTemperature() {return temperature;}public String getWeather() {return weather;}public WeatherIdEntity getWeather_id() {return weather_id;}public String getWind() {return wind;}public String getWeek() {return week;}public String getDate() {return date;}public static class WeatherIdEntity {private String fa;private String fb;public void setFa(String fa) {this.fa = fa;}public void setFb(String fb) {this.fb = fb;}public String getFa() {return fa;}public String getFb() {return fb;}@Overridepublic String toString() {return "WeatherIdEntity{" +"fa='" + fa + '\'' +", fb='" + fb + '\'' +'}';}}@Overridepublic String toString() {return "FutureEntity{" +"temperature='" + temperature + '\'' +", weather='" + weather + '\'' +", weather_id=" + weather_id +", wind='" + wind + '\'' +", week='" + week + '\'' +", date='" + date + '\'' +'}';}}@Overridepublic String toString() {return "ResultEntity{" +"sk=" + sk +", today=" + today +", future=" + future +'}';}}@Overridepublic String toString() {return "WeatherData{" +"resultcode='" + resultcode + '\'' +", reason='" + reason + '\'' +", result=" + result +", error_code=" + error_code +'}';} }總結
最后總結一下,通過使用mvp對代碼進行分層之后,模塊化更加的清楚,假如要換網絡框架,需要修改model層和api層的代碼,其他的層的代碼都不需要再動,這樣各層之間保持單一職責。代碼的易讀性變得更強了。
代碼的下載地址
代碼的運行效果:
歡迎大家查看。如果有問題直接回復。
總結
以上是生活随笔為你收集整理的Android中RxJava+Retrofit2.0+MVP模式的整合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 日期操作 增减天数、时间转换
- 下一篇: 八、图形与图像处理(2)