preface

The official Android architecture component was announced at Google I/O in May this year, and was in beta until November. Due to my busy work, I only read similar articles during this period, but I did not use them in the actual project, let alone read the source code. So the use of these components is very unfamiliar, but also feel that these components are very lofty, very mysterious!

Until November, when the official Android architecture component was released, and Google built the lifecycle component of the Official Android Architecture component into the Support Library after V26.1.0, I think it was the trend. Since Google believes so, it’s time for me to learn a wave and introduce them into the MVPArms framework

Github: Your Star is my motivation ✊

A simple introduction

Since I wanted to introduce Android official architecture components into the MVPArms framework, I carefully studied all the source code of Android official architecture components except Room to see if the whole component is suitable for the introduction of MVPArms framework

After learning the source code, I found that the Android official architecture component is not so sophisticated as imagined, the principle is that we will use knowledge points in daily development, then I will briefly introduce the Android official architecture component in the beginning of the article

Lifecycles

The Lifecycle component is the core component of the official Android architecture component. It can bind various instances as observers to lifecycle components such as activities and fragments. Both LiveData and ViewModel are based on this component. In short, you register an instance that requires a binding lifecycle with the component, and the component notifies the instance when one of the lifecycle methods you specify executes

There are a lot of scenarios. For example, in the MVP architecture, you need to have Presenter initialize some actions when the Activity executes onCreate, Instead of calling an initialization method of Presenter in the Activity’s onCreate, you can use the official lifecycle component to do this. When the Activity executes onDestroy, you need to release some of the object’s resources. Lifecycle components can also be used

LiveData

LiveData has two functions. The first function is the observer mode, which notifies all previously registered observers when Value changes. The second function is the life-cycle component binding with life-cycle components such as activities and fragments. Stop or resume previous events when the life cycle changes

In short, when a page successfully requests network data and needs to synchronize the UI, but the page is no longer visible, the UI synchronization operation will stop

ViewModel

The ViewModel has two functions. The first function allows the ViewModel and the data in the ViewModel to survive the reconstruction of an Activity caused by a screen rotation or configuration change, after which the data can continue to be used. The second feature makes it easy for developers to communicate and share data between fragments, activities and fragments

An overview of the official architecture components

Usage is not much said, there are too many such articles and Demo, understand their function and application scenario, we didn’t know whether they are really suitable for their own needs, rather than blindly following, let me to analyze how I investigate new technology, and how to determine whether these new technologies is necessary to apply to your own project

Lifecycles

Now that I’ve introduced the capabilities of lifecycle components, I’ll examine whether lifecycle components are necessary to introduce my framework, MVPArms

When I talk about the lifecycle, I think about the traditional MVP I used in the project is it really convenient or cumbersome? One of the topics discussed in

There are two popular MVP architectures in the market. The first one is an Activity or Fragment as a View, abstracting it from a Presenter layer. The second one is an Activity or Fragment as a Presenter. Abstract a View layer

The framework represented by the first type is MVPArms, and the framework represented by the second type is TheMVP. Of course, TheMVP architecture of the first type is the most widely used in the market, so what are the advantages of the second type?

As I mentioned in the previous article, there are two main advantages: easy reuse of views and the ability to bind directly to the Activity or Fragment lifecycle, so that you can use the Activity or Fragment lifecycle without having to do extra callbacks. Of course, there are also shortcomings, I also introduced in the article, interested can go to see

The first type of MVP architecture does not have the advantage of being directly tied to the Activity or Fragment lifecycle, so I envy the second type of MVP architecture. This is the biggest difference between the two types of MVP architecture, but you would be right. Using life cycle components now makes it easy for the first type of MVP architecture to take advantage of the binding life cycle, and now the first type of MVP architecture will be even more powerful

After the above analysis, I believe that lifecycle components are necessary for my framework to make daily development easier

LiveData

LiveData and RxJava are both based on the Observer mode, and there is some overlap. Google also makes it clear in the official documentation that if you are using RxJava, Agera and similar libraries, as long as you handle the lifecycle of the data stream correctly, You can continue to use them instead of LiveData

Note: If you are already using a library like RxJava or Agera, you can continue using them instead of LiveData. But when you use them or other approaches, make sure you are handling the lifecycle properly such that your data streams pause when the related LifecycleOwner is stopped and the streams are destroyed when the LifecycleOwner is destroyed. You can also add the android.arch.lifecycle:reactivestreams artifact to use LiveData with another reactive streams library (for example, RxJava2).

From the official documentation, Google suggests libraries for RxJava, Agera, LiveData, etc. You should use only one

RxJava or LiveData?

It’s true that LiveData and RxJava overlap too much, and I quite agree with Google’s official advice to choose one or the other. There is no need to introduce both projects, and the MVPArms framework also introduces RxJava. Should I choose LiveData or RxJava in MVPArms framework?

So I carefully studied its source code, LiveData has two functions, notify the observer to update the data and stop and restore the events before the lifecycle, and Rxjava plus RxLifecycle, Rxjava plus AutoDispose, Or Rxjava plus lifecycle components can easily do things that LiveData can and cannot do with Rxjava’s powerful operators, depending on the events before the lifecycle stops and resumes

And RxJava is not only RxJava, it is also a huge ecological chain, RxCache, RxLifecycle, RxAndroid, RxPermission, Retrofit-Adapter and a large number of powerful derivative libraries, There are a lot of things we can do without it that are very inconvenient, and the fledgling LiveData will have no advantage over RxJava, and even be very rudimentary

So if I can only choose between LiveData and RxJava, I have no reason to choose LiveData

ViewModel

One feature in the ViewModel that really amazes me, and makes me curious, is that it allows the ViewModel and the data in the ViewModel to survive an Activity reconstruction caused by a screen rotation or configuration change, and then the data can continue to be used. This feature is useful and important, and since there was no official solution before, I felt it was necessary to introduce this feature into the MVPArms framework

In addition, it can also help developers easily realize communication and data sharing between fragments and activities and fragments, which is also the official solution I need

But as I delved further to incorporate it into the project, I found that Google had wrapped this functionality up and limited its use to the ViewModel

But I figured if Google can do this with viewModels in the MVVM framework, why can’t I extend this functionality to presenters in the MVP framework, and more?

So I carefully studied its source code, ready to modify the source code and package into a library, so that more developers can use these functions in more scenarios

Modify the ViewModel component

To transform the ViewModel component naturally to its entire source code analysis again, know its principle, just know how to start

Analysis of the source code

Limited space, to a simple analysis of the source code, the source code is actually a few classes, after layers of encapsulation, the core code is in a Fragment called HolderFragment,

It seems to me that the core principle of the ViewModel component is one line of code in the HolderFragment:

setRetainInstance(true);

Copy the code

SetRetainInstance (Boolean) is a Fragment method, and I’m sure many of you know what this means

Simply set this method to true to enable the current Fragment to survive the Activity rebuilding. If this method is not set or set to false, the current Fragment will also rebuild during the Activity rebuilding and be replaced by a new object

This means that as long as this method is set to true, the Fragment and any data in the Fragment will survive the Activity rebuilding

We place a ViewModel Map in the Fragment whose setRetainInstance(Boolean) is true. Naturally, all viewModels in the Fragment will be saved from Activity rebuilding

So we have our activities and fragments bound to a Fragment, and we store the ViewModel in the Fragment’s Map, and that’s how we implement the ViewModel component

How to transform

In order to understand how to do this, we need to be clear about the purpose of this transformation. The purpose of this transformation is to make ViewModel components available to Presenters and other modules, not just ViewModel, okay

The reason why Google’s official ViewModel component can’t be used in other modules is because Google has encapsulated the Map mentioned above, not provided it, and restricted the way ViewModel can be built

The ViewModel component makes it mandatory for a new ViewModel to inherit from its base class, and makes it mandatory for the developer to provide a Factory that indicates how the current ViewModel is built. The ViewModel component will, when appropriate, Take the initiative to build ViewModel instances from the Factory and put them into a Map

The entire build process is controlled by the ViewModel component and restricted to the ViewModel, so what I need to do is extend the way the Map and ViewModel are built to give more control to outside developers

practice

After the above analysis, the train of thought and plan have, then how to realize the train of thought and plan

So I combined the above analysis of the ideas and programs of the official source code for transformation and do the appropriate optimization, LifecycleModel was born in this way

This article is mainly about before the completion of a goal, during the process of thinking and analysis from 0 to 1, as for the details if you are interested in it or go to see my source code, ha ha, notes very detailed oh!

Github: Your Star is my motivation ✊

conclusion

A new technology is really suitable for yourself or have to, should not blindly follow suit, if you only know the technology very fire, and then go with it, don’t know why I use it, with its benefits, then you will fall into the plight of passive learning, have been studying, but always feel couldn’t keep up with the progress of The Times, scared, This is the situation that most modern technologies exist in

Hit the pit

I also ran into some problems using ViewModel components in real projects, which cost me a lot of time, so it’s worth sharing to save you some of the detour

Potholes encountered when fetching ViewModel from Activity:
  • In the Application. The onActivityCreated ActivityLifecycleCallbacks method gets the ViewModel, Activity every reconstruction, The retrieved ViewModel is a new instance of the rebuilt ViewModel, and the ViewModel and the data in the ViewModel are not immune to Activity reconstruction, so do not retrieve the ViewModel in this method

  • The Activity’s onDestroy method cannot get the ViewModel, and an error is reported

}}}}}}}}}}}}}
  • In FragmentManager. FragmentLifecycleCallbacks the onFragmentAttached method to derive the ViewModel also can appear when the situation and Activity, The retrieved ViewModel is a new instance of the rebuilt ViewModel. The ViewModel and the data in the ViewModel are not immune to Activity rebuilding, so do not retrieve the ViewModel in this method either

  • In FragmentManager. FragmentLifecycleCallbacks onFragmentDestroyed method also can’t get in the ViewModel, complains

  • Unable to get ViewModel in Fragment onDestroy method, an error is reported

Hello, my name is Jessyan. If you like my articles, you can follow me on the following platforms

  • Making: github.com/JessYanCodi…
  • The Denver nuggets: juejin. Cn/user / 976022…
  • Jane: www.jianshu.com/u/1d0c0bc63…
  • Weibo: weibo.com/u/178626251…

Author: JessYan link: https://www.jianshu.com/p/963a9d146da7

Read more

How to choose between MVC, MVP and MVVM patterns?

Preamble to Android: MVP Architecture Exploration Tour – Basics

I can’t write MVP structure after reading it

MVP design in-depth analysis +NDK technology FFmpeg application

Take you through the MVP architecture patterns to give your project a more layered feel

Welcome to pay attention to my public number: Terminal RESEARCH and development Department, exchange and learn together!