Android developers the necessary skills would you? MVVM latest learning experience!

Foreword

In previous years the rise of MVVMarchitectural 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 MVVMdeveloping even so soon, it is already one of the skills necessary for the Android developers.

text

DataBindingIn the beginning stages, I was most troublesome is the problem of data processing, often in order to display the data, I want to XMLbind in Nmultiple fields, if it is above the average of a project, there are even more boring issues, such as:

  • You XMLmay need urgent ifor switchsuch judgments;
  • Unexpected null pointer

In 2018, the Googlelaunch of JetPackthe library, which ViewModel+LIveDatafinally MVVMpushed to new heights.

ViewModel

Use ViewModel need to rely on lifecyclelibraries:

  implementation "android.arch.lifecycle:viewmodel:x.x.x"
  implementation "android.arch.lifecycle:extensions:x.x.x"

ViewModelThere are two main methods of creation:

  // 获取FragmentActivity共享的ViewModel
  ViewModelProviders.of(FragmentActivity).get(ViewModel::class.java)

  // 获取FragmentActivity共享的ViewModel
  ViewModelProviders.of(Fragment).get(ViewModel::class.java)

ViewModelShared 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 Applicationlevel ViewModel, currently is not supported, you can customize Applicationto hold a ViewModel, or using the Singleton pattern.

ViewModel problem

1, the expansion of data sharing scenarios.

General data sharing is Activitythe Fragmentdata transfer, the traditional approach is used setArguments(Bundle), this method has the following drawbacks:

  • It can be unpredictable setArgumentswill Fragmentof which cycle is completed, to be abnormal judgment;
  • setArgumentsThe data change may be found, if Activitythe direct setting Fragmentof data, coupling high;
  • When more data, Fragmentthere 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 ViewModelto take in:

  • New additional data transfer, without modifying Activitythe setArgumentscode Fragmentmethod 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 Viewcan get ViewModel, so some functional coupling is very strong custom Viewdevelopment easier. But note that Viewthe contextcontext is Activitythe type (will not be Fragment), you can only use the Activitylevel of data sharing.

2, to solve the problem DataBinding view display.

If the view requires a lot of data, then XMLit 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 DataBindingsupport for the ternary operator to meet the needs if judgments, but it is clear that XMLthe maintenance logic than Javaor Kotlinmuch more difficult (no spelling error, etc.). So we need to put some code from very XMLisolated, ViewModelvery 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 ViewModelthe 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. LiveDataIt can be the perfect solution to this problem.

We need to add LiveDatadependencies:

  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();
          });

LiveDataThe subclasses are MutableLiveData, internal valueproperty holds the latest value, subscription LiveDatachanges, 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

ownerUsed directly Activityor Fragmentcan be. If you do not understand Lifecyclethe use, you can look at the relevant information.

to sum up

Finally, I drew a diagram architecture, summed up what the latest MVVMuse of architecture:

Activity: Deal with UIthe 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 UIview, hold ViewModelfor data display. If the page function is more complex, it can ViewModeland DataBindingsubdivided 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

Published 168 original articles · won praise 71 · views 20000 +

Guess you like

Origin blog.csdn.net/Aerfa789/article/details/104805814