1. Schema definition

Define a one-to-many dependency between objects, where every time an object changes state, all dependent objects are notified and automatically updated.

2. Observer mode application in Android source code

In Android source code, we contact more should be RecyclerView and ListView, and its matching Adapter, there is a refresh list notifyDataSetChanged() method, then, how to refresh the list of this method? First of all, the observer mode involves three operations: registering (adding) the observer, unregistering the observer, and notifying the observer of updates. When did RecyclerView implement the above operation?

RecyclerView.java

public void setAdapter(Adapter adapter) {
        // bail out if layout is frozen
        setLayoutFrozen(false);
        setAdapterInternal(adapter, false.true);
        requestLayout();
    }
    
private void setAdapterInternal(Adapter adapter, boolean compatibleWithPrevious,
            boolean removeAndRecycleViews) {
        if(mAdapter ! = null) { mAdapter.unregisterAdapterDataObserver(mObserver); mAdapter.onDetachedFromRecyclerView(this); }if(! compatibleWithPrevious || removeAndRecycleViews) { removeAndRecycleViews(); } mAdapterHelper.reset(); final Adapter oldAdapter = mAdapter; mAdapter = adapter;if(adapter ! = null) {/ / 1. See here adapter. RegisterAdapterDataObserver (mObserver); adapter.onAttachedToRecyclerView(this); }if(mLayout ! = null) { mLayout.onAdapterChanged(oldAdapter, mAdapter); } mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious); mState.mStructureChanged =true;
        setDataSetChangedAfterLayout();
    }
Copy the code

In the above code adapter. RegisterAdapterDataObserver (mObserver); This method belongs to the RecyclerView internal Adapter class

public abstract static class Adapter<VH extends ViewHolder> {
    public void registerAdapterDataObserver(AdapterDataObserver observer) {
            mObservable.registerObserver(observer);
        }
        
    public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
            mObservable.unregisterObserver(observer);
        }
        
    public final void notifyDataSetChanged() { mObservable.notifyChanged(); }}Copy the code

When we update RecyclerView data sources, the implementation of the adapter. The notifyDataSetChanged (); Method, and what does this method do?

RecyclerView Internal class Adapter

public final void notifyDataSetChanged() {
            mObservable.notifyChanged();
        }
Copy the code

RecyclerView internal AdapterDataObservable

static class AdapterDataObservable extends Observable<AdapterDataObserver> {
       
        public void notifyChanged() {
            // since onChanged() is implemented by the app, it could do anything, including
            // removing itself from {@link mObservers} - and that could cause problems if
            // an iterator is used on the ArrayList {@link mObservers}.
            // to avoid such problems, just march thru the list in the reverse order.
            for(int i = mObservers.size() - 1; i >= 0; i--) { mObservers.get(i).onChanged(); }}}Copy the code

RecyclerView internal class AdapterDataObserver

public abstract static class AdapterDataObserver {
        public void onChanged() {
            // Do nothing
        }
        
}
Copy the code

Remember the parameters we registered for the method above? It’s an AdapterDataObserver object

adapter.registerAdapterDataObserver(mObserver);
Copy the code

So, what is this mObserver?

private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver();
Copy the code

RecyclerView Internal class RecyclerViewDataObserver

private class RecyclerViewDataObserver extends AdapterDataObserver {
        RecyclerViewDataObserver() {
        }

        @Override
        public void onChanged() {
            assertNotInLayoutOrScroll(null);
            mState.mStructureChanged = true;

            setDataSetChangedAfterLayout();
            if(! mAdapterHelper.hasPendingUpdates()) { requestLayout(); }}}Copy the code

Here, RecyclerView will update the list with operations such as requestLayout.

The above is the source code analysis of RecyclerView refresh list, using the observer design mode, for this, we can also use the mode to deal with some of the observed and observed relationship between the scene.

3. Take the public account push as an example to introduce the simplified usage of observer design mode

Observer: The observer needs to be pushed

The operation interface that the observer has

public interface IWXUser {
    public void push(String article);
}
Copy the code

The observer

public class WXUser implements IWXUser {

    private String name;

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

    @Override
    public void push(String article) {
        System.out.println(name + "Received an article:"+ article); }}Copy the code

Observed: All kinds of public accounts

Public class WXPublicObservable {// Public List<IWXUser> mWXUsers; publicWXPublicObservable(){ mWXUsers = new ArrayList<>(); } /** * subscribe */ public void register(IWXUser wxUser){mwxusers.add (wxUser); } /** * unsubscribe * @param wxUser */ public void unregister(IWXUser wxUser){mwxusers.remove (wxUser); } /** * @param article */ public void update(String article)for(IWXUser wxUser : mWXUsers) { wxUser.push(article); }}}Copy the code

The specific observed

public class WXxxxObservable extends WXPublicObservable {
    private String article;

    public String getArticle() {
        return article;
    }

    public void setArticle(String article) { this.article = article; Update (article); }}Copy the code
3. Introduction to usage
Public class Client {public static void main(String[] args){// wechat public id - specific observable - XXX WXxxxObservable WXxxxObservable =  new WXxxxObservable(); WXUser vegen = new WXUser("vegen");
        WXUser xiaoming = new WXUser("Xiao Ming"); Wxxxxobservable. register(vegen); WXxxxObservable.register(xiaoming); / / # WeChat public - push articles WXxxxObservable setArticle ("I am The article Bara-bara-1."); No. / / WeChat public - user unsubscribe public WXxxxObservable. Unregister (vegen); / / # WeChat public - push articles WXxxxObservable setArticle ("I am The article, Blah, blah, blah."); }}Copy the code

Vegen and Xiaoming students can receive the tip of article Barabala 1, vegen later cancelled the subscription, only Xiaoming students received the tip of article Barabala 2.