Foreword
In previous years the rise of MVVM
architectural design patterns, the most representative of the frame is DataBinding
, although this architecture design is very innovative, but still in use, there are many pain points, so I thought this short period of time may not be too popular design architecture.
Recently took over the new project, is used MVVM
, only to find only one or two years of effort MVVM
developing even so soon, it is already one of the skills necessary for the Android developers.
text
DataBinding
In the beginning stages, I was most troublesome is the problem of data processing, often in order to display the data, I want to XML
bind in N
multiple fields, if it is above the average of a project, there are even more boring issues, such as:
- You
XML
may need urgentif
orswitch
such judgments; - Unexpected null pointer
In 2018, the Google
launch of JetPack
the library, which ViewModel+LIveData
finally MVVM
pushed to new heights.
ViewModel
Use ViewMode
l need to rely on lifecycle
libraries:
implementation "android.arch.lifecycle:viewmodel:x.x.x"
implementation "android.arch.lifecycle:extensions:x.x.x"
ViewModel
There are two main methods of creation:
// 获取FragmentActivity共享的ViewModel
ViewModelProviders.of(FragmentActivity).get(ViewModel::class.java)
// 获取FragmentActivity共享的ViewModel
ViewModelProviders.of(Fragment).get(ViewModel::class.java)
ViewModel
Shared range are mainly two: one is FragmentActivity
, one is Fragment
, you can choose to share a range according to their needs. If you want a Application
level ViewModel
, currently is not supported, you can customize Application
to hold a ViewModel
, or using the Singleton pattern.
ViewModel problem
1, the expansion of data sharing scenarios.
General data sharing is Activity
the Fragment
data transfer, the traditional approach is used setArguments(Bundle)
, this method has the following drawbacks:
- It can be unpredictable
setArguments
willFragment
of which cycle is completed, to be abnormal judgment; setArguments
The data change may be found, ifActivity
the direct settingFragment
of data, coupling high;- When more data,
Fragment
there will be a lot of variables that affect the readability and maintainability.
Use ViewModel
, to avoid more embarrassing situation, what data is needed from you ViewModel
to take in:
- New additional data transfer, without modifying
Activity
thesetArguments
codeFragment
method do not write the received data; - Reduce data transfer, regardless of whether you want to remove temporarily unused code;
- When fetching data, note the validity of the data, you can do the judgment;
In addition, Custom View
can get ViewModel
, so some functional coupling is very strong custom View
development easier. But note that View
the context
context is Activity
the type (will not be Fragment
), you can only use the Activity
level of data sharing.
2, to solve the problem DataBinding view display.
If the view requires a lot of data, then XML
it will become more and more bloated, and the urgent need to add some simple judgments, such as:
If A is empty is displayed B, if B is empty on the first C, if C is empty ...
Although DataBinding
support for the ternary operator to meet the needs if judgments, but it is clear that XML
the maintenance logic than Java
or Kotlin
much more difficult (no spelling error, etc.). So we need to put some code from very XML
isolated, ViewModel
very qualified for this role.
before fixing:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="A"
type="String" />
<variable
name="B"
type="String" />
<variable
name="C"
type="String" />
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="4"
android:ellipsize="middle"
android:text="A != null ? A : B != null ? B : C" />
...
</layout>
Modified:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewModel"
type="ViewModel" />
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="4"
android:ellipsize="middle"
android:text="@{viewModel.getShowContent()}" />
...
</layout>
LiveData
Just now we have discussed ViewModel
the best way of usage, but there is a problem is not resolved, and that is the problem of data update, the solution to this problem is to observer mode, but if you did not deal with the observer's registration reconciliation tie is prone to memory overflow. LiveData
It can be the perfect solution to this problem.
We need to add LiveData
dependencies:
implementation "androidx.lifecycle:lifecycle-livedata:2.1.0"
The following is a simple example:
// 名为openDrawer的Boolean类型的LiveData
public final MutableLiveData<Boolean> openDrawer = new MutableLiveData<>();
// 更新openDrawer
openDrawer.setValue(true)
// 观察openDrawer 的值的变化
openDrawer.observe(this, aBoolean -> {
Toast.makeText(this, "${aBoolean}", Toast.LENGTH_SHORT).show();
});
LiveData
The subclasses are MutableLiveData
, internal value
property holds the latest value, subscription LiveData
changes, direct call LiveData.observe()
:
void the observe public (@NonNull LifecycleOwner owner, @NonNull the Observer <? Super T> the Observer)
owner: registration period, will be destroyed when the owner, unbundling observer.
observer: observed value of the callback function is changed
owner
Used directly Activity
or Fragment
can be. If you do not understand Lifecycle
the use, you can look at the relevant information.
to sum up
Finally, I drew a diagram architecture, summed up what the latest MVVM
use of architecture:
Activity
: Deal with UI
the problem, but to do so should be avoided as far as possible consistent use DataBinding
.
ViewModel
: Save the page requires data, complex functions can be split into multiple words.
DataBinding
: Processing UI
view, hold ViewModel
for data display. If the page function is more complex, it can ViewModel
and DataBinding
subdivided again.
Finally something to say
I enclose my Android core technology learning syllabus, access to relevant content to play with my GitHub: https://github.com/Meng997998/AndroidJX
For advanced this way, the learning will pay off!
You take your time to invest in learning, it means that you can gain skills, have the opportunity to increase revenue.
Here to share my Android PDF Daquan learn to learn, learn this Android PDF Daquan really contain all aspects, and contains basic Java knowledge, the basis of Android, Android Advanced extension, and so on collection algorithm
My collection this study, can effectively help you grasp the knowledge points.
In short we are also here to help enhance learning advanced, but also saves you the time to learn online search data can also be shared with close friends studying together