当前位置:网站首页>Create a life cycle aware MVP architecture
Create a life cycle aware MVP architecture
2022-07-24 19:24:00 【Martin-Rayman】
I haven't written for a long time Blog 了 , In the past two years, I have accumulated a lot of knowledge and summary . Also achieved a lot of business , And Optimization for some businesses , I found that some knowledge can still be shared , It's just that I've been struggling before whether I will be looked down upon , After that, I found that I was worried too much . After all, let it out , The thoughts of different programmers come together , Maybe this framework can develop faster 、 Stable .
Maybe it will be two days later , Or update it at the speed of two articles a week .
I won't say much about it , First release a life cycle perception written by yourself MVP framework
(PS: The current architecture is directly applied to an online project , The results are also quite fruitful , Combined with their own packaging BaseMVPActivity,BaseMVPFragment A set of components is used , It's also beautiful .)
Life cycle aware MVP? Cover ? Or simple MVP?
What is? MVP? I believe you have used all the friends who can click in MVP 了 .
As for what is life cycle awareness ? Let's take a look at such a scene :
stay Presenter Layer handles business logic , More or less, it will involve network requests , If you use OkHttp、 Or is it Retrofit+RxJava As a network request , Then there will be asynchronous request callback UI The situation of , But we know that OkHttp He's not with Context Lifecycle bound ( Read the source code ),Retrofit+RxJava Yeah , Unless you add RxLifeCycle Component support , however RxLifeCycle There is a problem , I need it bindActivity, So this Activity How to pass it in ?
Original MVP Design mode of , Is to make Presenter Layers are imperceptible View Layer of Context There is , If you get through this process , It is no different from increasing MVP Complexity .
Here are RxLifeCycle Use ( This bindActivity How to pass the object of ?)
myObservable
.compose(RxLifecycleAndroid.bindActivity(lifecycle))
.subscribe();So here's the problem , Because of me Presenter The layer doesn't know Activity perhaps Fragment Life cycle of , If during the period of requesting callback , my Activity perhaps Fragment It needs to be destroyed , But because the request callback occupies View layer , So our Activity and Fragment There is a memory leak , In case of multiple memory leaks , Null pointer exceptions may also occur directly ( Because of the leak Activity Some controls may have been recycled , But continue to call View Layer control .) that App Just directly crash It fell off .
We all know OkHttp The request inside can be passed
OkHttpClient.dispatcher().cancelAll()Go and cancel the request , and Retrofit+Rxjava You can go through Observer Medium onSubscribe function , Through one Disposable List record request , Then go through the cancellation at the right time Ok 了 .
The right time ? Where is the right time ?
Buckle your head with your toes and think , Only in Activity perhaps Fragment Of onDestory It's time to call back .
The time has come , How can the life cycle start from View Layer passed to Presenter The floor ? To coincide with AndroidJetPack( It will be changed into AndroidX 了 ) The birth of , Make me have this idea to encapsulate a LifeCycleMVP Framework .
Google Address :https://developer.android.com/jetpack/
Because the company can climb over the wall , So all I read are English documents . About JetPack The components of , I will open another chapter to write .


LifeCycle As Google JetPack A construction tool under the framework ,Google Is also distressed Android developer , Know perfectly well Android In development Activity and Fragment The problem of life management . Specially except for one set LifeCycle For our use .
The above meaning is probably :LifeCycle Is a lightweight lifecycle management component , By listening for callbacks , Realize the monitoring and callback of the life cycle . Such as management Activity and Fragment My life .
In fact, it is also very easy to use , It's simple . Because in AppCompatActivity It supports LifeCycle Component . So twoorthree sentences of code will fix the response of the life cycle
For now LifeCycle Three classes of components :
LifeCycleOwner: Life cycle holder , An interface . Used to provide lifecycle related callbacks (Activity The last one is called SupportActivity, It implements the current interface , Used to provide current LifeCycleOwner object )
LifeCycleObserver: Life cycle observer , An interface , Used to implement and listen for lifecycle callbacks
LifeCycleRegistery: Lifecycle registry , It is mainly related to life holders and observers 、 Control which observer the event callback to 、 Life cycle binding processing .
The detailed implementation can see the source code by yourself ( It won't be complicated ), You can also jump here : To be added
gradle quote :compile "android.arch.lifecycle:extensions:1.1.1"
Foreplay is enough , Now is the time to roll up the code .
First MVP In the development mode , Let's first define a set MVP Layer protocol ,IBaseView,IBasePresenter.
Define a IBaseView First , It can be used for unified management View The layer object .
It doesn't hurt what function to implement , It can be realized according to your own business needs .
IBaseView.java
/**
* @Author:Rayman
* @Date:2018/10/17
* @Description: View Implemented interface
*/
public interface IBaseView {
/**
* Display error , For example, no data 、 Network error and so on .
*
* @param msg Error copywriting tips
*/
void showErrorMsg(String msg);
}View Layer callback does it by itself ,Presenter Layer callback is the key .Presenter Layer I define four functions :
binding View、View layer onCreate Callback ( Considering that there are P The layer needs to use this lifecycle callback )、View layer onDestroy Callback 、 Other lifecycle callbacks
IBasePresenter.java
/**
* @Author:Rayman
* @Date:2018/10/17
* @Description:Presenter The interface of .
* Default implementation AndroidX LifeCycle Components
**/
public interface IBasePresenter<T> extends LifecycleObserver {
/**
* binding View
*
* @param view
*/
void setView(@NonNull T view);
/**
* View layer OnCreate Event callback
*/
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onViewCreate();
/**
* View layer onDestroy Event callback
*/
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onViewDestroy();
/**
* Callback during life cycle switching
*/
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onLifeCycleChange(@NonNull LifecycleOwner owner,
@NonNull Lifecycle.Event event);
}
After finishing according to the above definition , Preliminary LifeCycleMvp The frame is out , The rest is how to get there MVP And how to realize the binding of life cycle .
Binding lifecycle
Binding life cycle ~ Need to cooperate with BaseActivity perhaps BaseFragment Use .
I will release one here BaseMVPActivity, The same is true for other uses .
Mainly inherited BaseActivity, And then it came true IBaseView Interface , An internal IBasePresenter Member variables of .
And then in onCreate When the lifecycle callback , Conduct View Layer and the Presenter The binding of , At the same time, it also binds the life cycle
/**
* @Author:Rayman
* @Date:2018/10/17
* @Description: Inherit BaseActivity, Integrate MVP framework
*/
public abstract class BaseMvpActivity<D> extends BaseActivity implements IBaseView<D> {
/**
* description:MVP Layer Association
**/
private IBasePresenter mPresenter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
initMvp();
super.onCreate(savedInstanceState);
}
/**
* initialization MVP framework
*/
private void initMvp() {
mPresenter = createPresenter();
if (mPresenter != null) {
mPresenter.setView(this);
// initialization MVP When , Add lifecycle listener
getLifecycle().addObserver(mPresenter);
}
}
/**
* Set the current module P layer , Need to be in initView Previous call
*
* @return
*/
protected abstract IBasePresenter createPresenter();
}After lifecycle binding , All that is left is to use .
How to use ?
First, implement a business logic Presenter layer , And then inherit IBasePresenter.
For the convenience of demonstration , I just picked up one of the projects Contract class
IUserChangeAccountContract.java
/**
* @Author:Rayman
* @Date:2018/10/21
* @Description: User module --- Change your account number
*/
public interface IUserChangeAccountContract {
interface IUserChangeAccountModel {
/**
* description: Change your account number
**/
Observable<CommonData> changeAccount(String realName , String account);
}
interface IUserChangeAccountPresenter extends IBasePresenter<IUserBindAliAccountView> {
void changeAccount(String realName , String account);
}
// Now this IBaseLoadingView It's also inheritance IBaseView Of .
interface IUserChangeAccountView extends IBaseLoadingView<CommonData> {
void changeAccountSuccess(String msg);
}
}And then we'll see IUserChangeAccountPresenter The implementation of the
UserChangeAccountPresenter.java
/**
* @Author:Rayman
* @Date:2018/10/21
* @Description: User module ---P layer --- Change your account number
*/
public class UserBindAliAccountPresenter implements IUserBindAliAccountContract.IUserBindAliAccountPresenter {
private IUserBindAliAccountContract.IUserBindAliAccountView mView;
private IUserBindAliAccountContract.IUserBindAliAccountModel mModel = new UserBindAliAccountModel();
private ArrayList<Disposable> mDisposableList = new ArrayList();
private int requestCount = 0;
@Override
public void setView(IUserBindAliAccountContract.IUserBindAliAccountView view) {
mView = view;
}
@Override
public void onViewCreate() {
LogUtils.error("View establish ");
}
@Override
public void onViewDestroy() {
for(int i = 0,size = mDisposableList.size();i < size; i++){
Disposable disposed = mDisposableList.get(i);
disposed.dispose();
}
LogUtils.error("View Destruction request :" + requestCount);
}
@Override
public void onLifeCycleChange(LifecycleOwner owner, Lifecycle.Event event) {
LogUtils.error("View Life cycle transformation :" + event.name());
}
@Override
public void changeAccount(String realName,String account) {
mView.showLoading();
requestCount++;
mModel.changeAccount(realName, account)
.subscribe(new RxSubscriber<CommonData, IUserBindAliAccountContract.IUserBindAliAccountView>(mView) {
@Override
public void onSubscribe(Disposable d) {
super.onSubscribe(d);
mDisposableList.add(d);
}
@Override
public void onNext(CommonData t) {
super.onNext(t);
mView.bindAliAccountSuccess(" Binding success ");
UserUtils.updateBindAccount(account, realName);
}
});
}
}
This is the whole process , In the above example, I just use Retrofit+RxJava The way of request . And then in onSubscribe Lieutenant general RxJava Add event handling to a list , And then in ViewDestroy When traversing and destroying .
Finally, let's take a look at Log The output of also passes AndroidProfiler Look at the , Whether multiple requests will cause Activity Memory leak .
To be added ----
Okay ~ The code is just as described above , Linkage next --- be based on LifeCycleMvp Re expansion , Then release a GitHub Open source library .
边栏推荐
猜你喜欢

Why are there loopholes in the website to be repaired

文献阅读:GoPose 3D Human Pose Estimation Using WiFi

Nacos introduction and console service installation
思源笔记 v2.1.2 同步问题

High speed ASIC packaging trends: integration, SKU and 25g+

Common problems of multithreading and concurrent programming (to be continued)

FPGA 20 routines: 9. DDR3 memory particle initialization write and read through RS232 (Part 2)

FPGA 20 routines: 9. DDR3 memory particle initialization write and read through RS232 (Part 1)
![[face to face experience of school recruitment] 8 real questions of pointer interview. Come and test how many you have mastered.](/img/2c/e687b224285aeee66dacace6331161.png)
[face to face experience of school recruitment] 8 real questions of pointer interview. Come and test how many you have mastered.

Machine learning_ Data processing and model evaluation
随机推荐
Machine learning_ Data processing and model evaluation
Wireshark simple filter rule
About core files
Nacos introduction and console service installation
FPGA 20个例程篇:9.DDR3内存颗粒初始化写入并通过RS232读取(上)
Hold the C pointer
Timed task framework
Cyberpanel free open source panel - high speed lscache free SSL Certificate - self built DNS and enterprise post office
LSTM and Gru of RNN_ Attention mechanism
JVM method call
What are the benefits of knowledge management in enterprises?
Mysql database, de duplication, connection
多线程与并发编程常见问题(未完待续)
【无标题】
Excel practice notes 1
Meshlab&PCL ISS关键点
MySQL sort. Sort by field value
MySQL final chapter
Cmake series tutorial 2 HelloWorld
In the spring of domestic databases