啥也不说了,先上效果图:
搭建流程:
引入依赖库
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.google.code.gson:gson:2.6.2'
使用Retrofit+Rxjava
1.录入请求url地址类
public class ApiConstants {
public static final class Urls{
public static final String BASE_URL = "http://live.ximalaya.com/";
public static final String BROADCAST = "live-web/v4/homepage";
}
public static final class Paths{}
public static final class Integers{}
}
2.接口请求,返回的是Rxjava带的Ovservable角色。
public interface ApiService {
@GET(ApiConstants.Urls.BROADCAST)
Observable<MainDataEntity> getBroadCast();
}
3.单例模式创建ApiService类,添加服务器地址,设置5秒请求超时。ApiService默认返回Call类型,但是需要直接转化Observable类型,此时需要添加addCallAdapterFactory(RxJavaCallAdapterFactory.create()) 。需要直接转化为需要的实体类,需要添加addCallAdapterFactory(RxJavaCallAdapterFactory.create())。
public class ApiManager {
private Retrofit retrofit;
private final int DEFUALT_TIMEOUT = 5;
private static ApiService apiService;
private ApiManager(){
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFUALT_TIMEOUT, TimeUnit.SECONDS);
OkHttpClient client = builder.build();
retrofit = new Retrofit.Builder()
.baseUrl(ApiConstants.Urls.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
apiService = retrofit.create(ApiService.class);
}
public static synchronized ApiService getApiService(){
if(apiService == null){
new ApiManager();
}
return apiService;
}
}
4.封装泛型实体类的观察者,统一处理结果。请求成功给下一层返回实体类。请求失败从HttpException中获取code设置对应的errorMsg。
public abstract class ApiCallBack<M> extends Subscriber<M>{
public abstract void onSuccess(M model);
public abstract void onFailure(String msg);
public abstract void onFinish();
@Override
public void onCompleted() {
onFinish();
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
if (e instanceof HttpException) {
HttpException httpException = (HttpException) e;
int code = httpException.code();
String msg = httpException.getMessage();
if (code == 504) {
msg = "网络不给力";
}
if (code == 502 || code == 404) {
msg = "服务器异常,请稍后再试";
}
onFailure(msg);
} else {
onFailure(e.getMessage());
}
onFinish();
}
@Override
public void onNext(M model) {
onSuccess(model);
}
}
加入Mvp
1.BaseView,规定所有Activity,fragment等容器的公共行为,例如显示加载框和隐藏。
public interface BaseView {
void showLoading();
void hideLoading();
}
一个具体view容器需要实现的功能,如加载数据成功和失败。
public interface MainView extends BaseView{
void getDataSuccess(MainDataEntity model);
void getDataFail(String msg);
}
2.Basepresenter,抽象的persenter业务处理层。关联抽象层view和抽象model,通过CompositeSubscription关联数据请求,并通过subscriber回调回view层。
public class BasePresenter<V> {
public V view;
private CompositeSubscription mCompositeSubscription;
protected ApiService apiService;
//将prerenter与view绑定
public void attachView(V view){
this.view = view;
apiService = ApiManager.getApiService();
}
public void detachView(){
this.view = null;
onUnsubscribe();
}
//RXjava统一取消注册,以避免内存泄露
public void onUnsubscribe(){
if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
mCompositeSubscription.unsubscribe();
}
}
public void addSubscription(Observable observable, Subscriber subscriber) {
if (mCompositeSubscription == null) {
mCompositeSubscription = new CompositeSubscription();
}
mCompositeSubscription.add(observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber));
}
}
- ObserveOn
specify the Scheduler on which an observer will observe this Observable
指定一个观察者在哪个调度器上观察这个Observable
- SubscribeOn
specify the Scheduler on which an Observable will operate
指定Observable自身在哪个调度器上执行
basepresenter的一个实现,做getBroadCast()请求,解析为MainDataEntity对象,回调给该view层。
public class MainPresenter extends BasePresenter<MainView>{
public MainPresenter(MainView view){
attachView(view);
}
public void loadData(){
view.showLoading();
addSubscription(apiService.getBroadCast(), new ApiCallBack<MainDataEntity>() {
@Override
public void onSuccess(MainDataEntity model) {
view.hideLoading();
view.getDataSuccess(model);
}
@Override
public void onFailure(String msg) {
view.getDataFail(msg);
}
@Override
public void onFinish() {
view.hideLoading();
}
});
}
}
3.MvpActivity绑定presenter,在销毁时解绑,调用onUnsubscribe()将rxjava统一取消注册,以避免内存泄露。至于BaseActivity功能根据项目业务需求进行封装。比如跳转,加载弹出框,是否全屏,频繁调用工具类等。
public abstract class MvpActivity<P extends BasePresenter> extends BaseActivity{
protected P mPresenter;
@Override
public void onCreate(Bundle savedInstanceState) {
mPresenter = createPresenter();
super.onCreate(savedInstanceState);
}
protected abstract P createPresenter();
@Override
protected void onDestroy() {
super.onDestroy();
//页面销毁时取消presenter绑定
if(mPresenter != null) mPresenter.detachView();
}
}
3.最后,Mainactivity实现功能。
public class MainActivity extends MvpActivity<MainPresenter> implements MainView {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPresenter.loadData();
}
@Override
protected MainPresenter createPresenter() {
return new MainPresenter(this);
}
@Override
public void getDataSuccess(MainDataEntity model) {
//打印部分数据
StringBuilder stringBuilder = new StringBuilder();
List<MainDataEntity.DataBean.CategoriesBean> list = model.getData().getCategories();
for(int i=0;i<list.size();i++){
stringBuilder.append(list.get(i).getName() + " ");
}
Toast.makeText(getApplicationContext(),stringBuilder.toString(),Toast.LENGTH_LONG).show();
}
@Override
public void getDataFail(String msg) {
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
}
这是一个基本的MVP架子,还缺失数据过滤,抽象实体类。后面我会写一些高仿项目系列来使用该框架并附上github链接。