Jetpack (AAC Framework) for Android Interviews in 2022

foreword

The Jetpack framework officially launched by Google has been around for a long time. Basically, new projects will use the MVVM + kotlin + coroutine architecture to build some new projects or refactor. Therefore, the AAC framework in the interview or more It is rarely mentioned that this article is mainly a high-level overview of several commonly used frameworks, and you need to check the source code by yourself

Lifecycle

  • Function: Extract from the Activity life cycle, provide API for monitoring (observer mode), use the state mode to save the current state and the events of the two steps before and after
  • Note: non-thread safe, call in the main thread
  • Source code implementation: A ReportFragment will be injected into ComponentActivity, which will distribute the life cycle (similar to Glide)
  • Annotation (OnLifecycleEvent) usage principle:
  • After 2.4, it has been deprecated, and it is recommended to set the monitoring method to achieve
  • Implement the LifecycleObserver interface, which is an empty interface, and then mark the OnLifecycleEvent annotation on the required method, for example, then call the @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)method Lifecycle#addObserver, which will construct one ObserverWithState, which will be called in the constructor of ObserverWithState Lifecycling#lifecycleEventObserver, and get all the marked methods through annotation reflection, in This method will be called through reflection when the life cycle is distributed
  • The annotation/inheritance interface is unified through ObserverWithStateand for easy calling; in its method, it will be obtainedLifecyclingdispatchEvent

Status and Events

distribution processimage-20220524174909957.png

LiveData

  • Function:
  1. Data with the ability to observe the lifecycle, itself observes Lifecycle, and provides an API as an observer to monitor data changes (triggered only when the lifecycle is valid)
  2. Used as an event bus - LiveDataBus

Source code analysis

Observe method

  • First, according to the called observe or observeForever, wrap the monitoring object once, and then add it to the observer collection. The packaging here is for subsequent unified operations (judging whether it is active, etc.); a monitoring object can only correspond to one lifecycle
  • Then, if it is observeForever, it will call to check the value status once for distribution (stickiness); if it is the observe method, it will be encapsulated into LifecycleBoundObserver (implemented LifecycleEventObserver), and add the event of listening to Livecycle, and then decide whether to distribute new values ​​according to the event (active state)

image-20220525232613966.png

Distribute news

  • postValue (switch to the main thread and call setValue)
  • setValue

Whether it is postValue or setValue, it will go to setValue, first update the value of LiveData, then add one to the version number, then traverse all observers, judge the life cycle and call the onChange method of qualified observers, pay attention to this traversal process , when the bound life cycle state changes, a round of judgment will also be performed (ObserverWrapper#activiStateChange)

// mDispatchingValue: 是否正在分发值
// mDispatchInvalidated 是否分发完成
// 通过这两个状态控制分发状态 及时更新最新的值
void dispatchingValue(@Nullable ObserverWrapper initiator) {
    
    
        // 如果正在更新值 mDispatchInvalidated 直接置为true 这样下面do while会再执行一次 更新最新的值
        if (mDispatchingValue) {
    
    
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        do {
    
    
            mDispatchInvalidated = false;
            if (initiator != null) {
    
    
                considerNotify(initiator);
                initiator = null;
            } else {
    
    
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
    
    
                    considerNotify(iterator.next().getValue());
                    // 说明有新值 直接中断重新开始
                    if (mDispatchInvalidated) {
    
    
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }
    
 // 真正的把值传递出去
 private void considerNotify(ObserverWrapper observer) {
    
    
        if (!observer.mActive) {
    
    
            return;
        }
      
        // 对观察者状态再次判断
        if (!observer.shouldBeActive()) {
    
    
            observer.activeStateChanged(false);
            return;
        }
        // 避免重复调用
        if (observer.mLastVersion >= mVersion) {
    
    
            return;
        }
        observer.mLastVersion = mVersion;
        observer.mObserver.onChanged((T) mData);
    }

image-20220525231247043.png

Event bus usage

  • LiveData can be stored in the form of Map and used as an event bus, but there is a problem that the default message is sticky (data backflow)
  • Solution: The reason for data backflow is that when an observer is added, the status of Lifecycle will be updated at this time, and the value will be further synchronized; at this time, the Version value of Observer can be modified to be the same as that of LiveData through reflection, so that the update will not be triggered

image-20220526175752195.png

ViewModel

  • Function: In the VM layer in MVVM, View and Model are isolated, and at the same time, it has the ability to sense life, and can automatically save data when the system configuration changes (rotation, etc.), and provides a clear method to clear data when the activity is destroyed
  • Save and reuse: use ComponentActivity#onRetainNonConfigurationInstanceand ComponentActivity#getLastNonConfigurationInstance, reassign one when the activity consumes and rebuilds ViewModelStore, this ViewModelStore is actually a Map (String-ViewModel) that stores the ViewModel, and when obtaining the ViewModel, it is also fetched from this ViewModelStore, if there is If not, create one through reflection and save it in this Map
  • Destruction monitor: ComponentActivityA LifecycleEvent monitor will be registered at the time of creation. When a destruction event is received and it is not a configuration change , the clear method of ViewModelStore will be called, and then the process of calling clear will be traversed in turn.
  • ViewModelStoreConsumption: Like onClear, it also listens to lifecycleEvent, and clears it when it receives a destruction event

image-20220527123903985.png
image-20220527123917221.png

summary graph

Please add a picture description

common interview questions

MVP and MVVM Advantages and Disadvantages

  • MVP: Evolved from MVC, decoupled, separated from the View layer, and reduced the burden on the Activity; however, MVP will generate a large number of interfaces and class files; the life cycle needs to be managed by itself; the View and the P layer are highly coupled and often require cooperation change
  • MVVM: M layer is completely focused on data; it is more low-coupling, VM does not hold View-related, and a lot of business logic can be reused in VM layer; but Databinding will make XML files difficult to reuse and difficult to debug
  • The biggest difference is that in MVP, the P and V layers hold each other, while in MVVM, the VM does not hold the View and no longer relies on the View layer, but observes data changes through the observer mode (LiveData, DataBinding, etc. )

The difference between ViewModel saved in Application and ViewModelScope

The difference in life cycle, one is the application life cycle and the other is the life cycle life cycle

How does ViewModel ensure that data is saved after Activity is destroyed

When the Activity is destroyed, AMS will call retainNonConfigurationInstancesthe method through the remote Binder, which will call onRetainNonConfigurationInstanceand getLastNonConfigurationInstancesave some configurations, including ViewModelStore, when the Activity is recreated, AMS will AMS#attachreassign the instance by

ViewModelProvider和ViewModelProviders

ViewModelProviders was used to create ViewModel in the early days. The new version has been deprecated. It is created directly using ViewModelProvider. The corresponding ViewModelStore is also managed by Activity/Fragment

Saving and restoring ViewModel

See the ViewModel article

How to understand MVVM

  • First of all, MVVM is an architectural model. In Android development, Google provides us with a set of jetpack frameworks to quickly implement MVVM (LiveData, Databinding, ViewModel), which handles a lot of repetitive work related to the life cycle for us. Eliminates a lot of repetitive code
  • I think the core of the AAC framework is Lifecycle. Taking Activity as an example, it obtains lifecycle events by injecting a fragment without UI, and then maintains a state machine in it, and the lifecycle perception capabilities of LiveData, ViewModel, etc. They are all controlled by the state maintained by Lifecycle

Guess you like

Origin blog.csdn.net/weixin_41802023/article/details/126019400