Explain the use advantages and disadvantages of Android observer mode in detail

  • 2021-12-05 07:34:07
  • OfStack

1. Introduction

Observer pattern (also known as publish-subscribe pattern (Publish/Subscribe) is a kind of behavioral pattern, which defines a one-to-many dependency relationship, so that multiple observer objects can listen to a topic object at the same time. This subject object notifies all observer objects when its state changes, enabling them to update themselves automatically. One of the important functions of this pattern is decoupling, which decouples the observer and the observer to make them less dependent

2. Use scenarios

In the scenario of association behavior, it should be noted that the association behavior is detachable rather than "combined"
Event multi-level trigger scenario
Cross-system message exchange scenarios, such as message queue and event bus processing mechanism

3. Simple implementation

Here we take the subscription of WeChat official account as an example. When WeChat official account updates its content, it will be pushed to readers who subscribe to the WeChat official account.


 // Observed person 
 public class Wechat extends Observable{
  public void postNewPublication(String content){
   setChanged();
   notifyObservers(content);
  }
 }

 // Observer 
 public class Reader implements Observer{
  public String name ;

  public Reader(String name) {
   this.name = name;
  }

  @Override
  public void update(Observable o, Object arg) {
   Log.i(TAG, "update: wechat is update content is :"+arg);
  }
 }
 
 public void test(){
  Wechat wechat=new Wechat();
  
  Reader reader1=new Reader("reader1");
  Reader reader2=new Reader("reader2");
  Reader reader3=new Reader("reader3");
  
  wechat.addObserver(reader1);
  wechat.addObserver(reader2);
  wechat.addObserver(reader3);
  
  wechat.postNewPublication("up up up");
 }

Note here that Observer and Observable are built-in classes in JDK, representing the observer and the observed.

4. Application of Observer Pattern in Android

notifyDataSetChanged for ListView and RecycleView

When we use ListView or RecycleView, if the data changes, we call the notifyDataSetChanged () method of Adapter, as shown below


 public void notifyDataSetChanged() {
  mDataSetObservable.notifyChanged();
 }

mDataSetObservable. notifyChanged is called inside the method, where mDataSetObservable is an instance of DataSetObservable


private final DataSetObservable mDataSetObservable = new DataSetObservable();

While DataSetObservable inherits from Observable, let's look at notifyChanged method of DataSetObservable


public class DataSetObservable extends Observable<DataSetObserver> {

public void notifyChanged() {
  synchronized(mObservers) {
   for (int i = mObservers.size() - 1; i >= 0; i--) {
    mObservers.get(i).onChanged();
   }
  }
 }
 }

You can see that the onChanged method of DataSetObserver is called, and DataSetObserver is a sampled class where mObservers. get (i) gets its subclass AdapterDataSetObserver.


class AdapterDataSetObserver extends DataSetObserver {
  private Parcelable mInstanceState = null;
  @Override
  public void onChanged() {
   mDataChanged = true;
   mOldItemCount = mItemCount;
   mItemCount = getAdapter().getCount();
   if (AdapterView.this.getAdapter().hasStableIds() && mInstanceState != null
     && mOldItemCount == 0 && mItemCount > 0) {
    AdapterView.this.onRestoreInstanceState(mInstanceState);
    mInstanceState = null;
   } else {
    rememberSyncState();
   }
   checkFocus();
   // Re-layout 
   requestLayout();
  }

  ...

  public void clearSavedState() {
   mInstanceState = null;
  }
 }

You can see that requestLayout is called in the onChanged method of AdapterDataSetObserver for relayout.

BroadcastReceiver

Broadcast in Android is also based on observer mode

5. Summary

Advantages of observer mode:

Decoupling the observer and the observed to cope with business changes Enhance the flexibility and scalability of the system

Disadvantages:

Development efficiency and operation efficiency should be considered when using. The program includes one observer and multiple observers. Development and debugging will be complicated, and the message notification in Java is executed sequentially by default. If one observer is stuck, the overall execution efficiency will be affected. In this case, asynchronous mode is generally considered.

The above is a detailed explanation of the use of Android Observer Mode and the pros and cons of the detailed content, more information about Android Observer Mode please pay attention to other related articles on this site!


Related articles: