mvp+retrofit
View:
视图,首先定义接口,定义接口先看需要做什么。
本例是想获得网络数据,所以定义方法:
void getHomeModel(HomeModel homeModel);
这个HomeModel是一个JavaBean,将网络数据,封装成一个bean对象。
所以,这个view的接口代码是:
public interface IMainView {
void getHomeModel(HomeModel homeModel);
}
实现这个接口的view是:
public class HomePageActivity extends AppCompatActivity implements IMainView{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void getHomeModel(HomeModel homeModel) {
}
}
model:
model主要用来处理数据。
所以他的接口就定义一个get和set:
public interface IModel {
public Observable<HomeModel> getInfo();
public void setInfo(String info);
}
这个Observable是RXJava的返回方式,后面用Retrofit请求网络的返回值。
所以model的实现类:
public class MainModel implements IMainImpl {
@Override
public Observable<HomeModel> getInfo() {
return observable;
}
@Override
public void setInfo(String info) {
}
}
presenter:
presenter相当于一个中转站,接受view端的请求,交给model处理,再将处理结果反馈给view.
所以presenter里面需要有这2个类的引用:
public class MainPresenter {
IMainView mView;
IModel mModel;
}
接下来,看具体的逻辑:
view需要请求网络获取数据,Presenter里面必须为他提供一个getNetWorkInfo()方法。
public void getNetWorkInfo() {
Observable<HomeModel> observable = mModel.getInfo();
}
最终数据是去model处理。
presenter里面设置构造方法:
public MainPresenter(IMainView iMainView) {
this.mView = iMainView;
mModel = new ModelImpl();
}
而view里初始化presenter对象,并调用getNetWorkInfo:
MainPresenter presenter = new MainPresenter(this);
presenter.getNetWorkInfo();
model接受presenter的请求后,通过retrofit请求网络。
public Observable<HomeModel> getInfo() {
Observable<HomeModel> observable = post();
return observable;
}
private Observable<HomeModel> post() {
Observable<HomeModel> observable = RetrofitHelper.getInstance().getServer().getHomeModel();
return observable;
}
此处用了retrofit+rxjava。
通过getHomeModel方法请求网络后,通知Observable的subscribe取得数据。
Observable<HomeModel> observable = mModel.getInfo();
observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<HomeModel>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(HomeModel homeModel) {
mHomeModel = homeModel;
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
mView.getHomeModel(mHomeModel);
}
});
通过
mView.getHomeModel(mHomeModel);
将数据传递给view。
具体代码如下:
https://github.com/doudousang/mvp/
参考文章:
mvp相关:
https://blog.csdn.net/briblue/article/details/52839242
https://www.jianshu.com/p/5c3bc32afa36
https://blog.csdn.net/qq_28057577/article/details/78295179
retrofit相关:
https://www.jianshu.com/p/ddd73eb6ffaa
https://www.jianshu.com/p/1463bc223cd8
以及第一次上传代码到github:
https://www.cnblogs.com/cxk1995/p/5800196.html
https://www.jianshu.com/p/103735801a2e