Android官方架构组件之LiveData + ViewModel + Room 源码分析一

简单使用案例:
MainActivity:

viewModel.getMessageObserver().observe(this, new Observer() {
    @Override
    public void onChanged(@Nullable MessageBean messageBean) {
        if (messageBean != null) {
            LogUtils.d(messageBean.toString());
        }
    }
});

MessageViewModel:

public class MessageViewModel extends ViewModel {

    private final MutableLiveData mMessageObserver = new MutableLiveData<>();

    public LiveData getMessageObserver() {
        return mMessageObserver ;
    }

    public void setHoroscopeId(int horoscopeId) {
        List characters = new ArrayList<>();
        characters.add(new MessageBean("body1"));
        characters.add(new MessageBean("body2"));
        characters.add(new MessageBean("body3"));
        characters.add(new MessageBean("body4"));

        mMessageObserver.setValue(characters.get(horoscopeId));
    }

    public void getProjectList() {
        DataRepository.getInstance().getProjectList(mMessageObserver , "1", 294);
    }
}

其中viewModel.getMessageObserver().observe(this, new Observer() )
中的this即SupportActivity :LifecycleOwner

SupportActivity implements LifecycleOwner

public interface LifecycleOwner {
    Lifecycle getLifecycle();
}

SupportActivity

public class SupportActivity extends Activity implements LifecycleOwner {

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }

    @CallSuper
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        super.onSaveInstanceState(outState);
    }

  
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

SupportActivity就是通过getLifecycle()获取 mLifecycleRegistry来标记当前Activity或Fragment的各种状态,其中ReportFragment.injectIfNeededIn(this)内部源码也是与mLifecycleRegistry.markState(Lifecycle.State.CREATED) 类似,状态的信息记录在mLifecycleRegistry对象内部。Activity的其他类型的事件如onCreate,onPause等都是通过getLifecycle()获取 mLifecycleRegistry对象调用mLifecycleRegistry内部方法来改变其状态的。

Fragment的状态更加容易看到,FragmentActivity即在Activity的生命周期中获取

FragmentActivity部分源码:

    @Override
    protected void onStop() {
        super.onStop();

        mStopped = true;
        markState(getSupportFragmentManager(), Lifecycle.State.CREATED);
        mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);

        mFragments.dispatchStop();
    }

    private static void markState(FragmentManager manager, Lifecycle.State state) {
        Collection fragments = manager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment == null) {
                continue;
            }
            fragment.mLifecycleRegistry.markState(state);
            markState(fragment.getChildFragmentManager(), state);
        }
    }

通过上面的简单分析,两个重要的类即 LifecycleRegistry extends Lifecycle:

下面是Lifecycle抽象类:

public abstract class Lifecycle {
  
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

  
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    @MainThread
    public abstract State getCurrentState();

    public enum Event {
        
        ON_CREATE,
      
        ON_START,
      
        ON_RESUME,
      
        ON_PAUSE,
       
        ON_STOP,
       
        ON_DESTROY,
       
        ON_ANY
    }

    public enum State {
       
        DESTROYED,

        INITIALIZED,

        CREATED,

        STARTED,

        RESUMED;

        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}

回到开始的案例:
LiveData.observe(this, new Observer);

    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        // 经典的装饰器模式,这里的设计很精妙,可以看出我们传入的Observer和 owner.getLifecycle().addObserver()是不同的。
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        // 判断是否已经添加过防止重复添加
        LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper);
        if (existing != null && existing.owner != wrapper.owner) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        owner.getLifecycle().addObserver(wrapper);
    }

这里我们传入的Observer和 owner.getLifecycle().addObserver()即 Activity中的Lifecycle 是不同的。
我们上面已经知道Activity中的Lifecycle是与生命周期相关的,通过Lifecycle.addObserver()可以监听到 Activity的生命周期 然后在LifecycleBoundObserver作出
相应的处理,具体的实现在LifecycleRegistry.addObserver中(Lifecycle实现类),最终会根据事件变化调用 mLifecycleObserver.onStateChanged(owner, event),

class LifecycleBoundObserver implements GenericLifecycleObserver {
    public final LifecycleOwner owner;
    public final Observer observer;

    LifecycleBoundObserver(LifecycleOwner owner, Observer observer) {
        this.owner = owner;
        this.observer = observer;
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        // 此处在组件如Activity onDestroy的时候自动移除观察者。
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            removeObserver(observer);
            return;
        }
        // immediately set active state, so we'd never dispatch anything to inactive
        // owner
        activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
    }
}

LifecycleBoundObserver.onStateChanged -> activeStateChanged -> dispatchingValue -> considerNotify(initiator) -> observer.observer.onChanged((T) mData);

最终调用的是我们传入的observer。

这样看来 LiveData 就没有什么特殊的了,把它看做一个普通的观察者模式的管理者即可,比如EventBus。

public abstract class LiveData {
    
    private static final Object NOT_SET = new Object();
    
    // LiveData 存取的值,即T, setValue,postValue 会强制转换为T。    
    private volatile Object mData = NOT_SET;
}

https://developer.android.com/reference/android/arch/lifecycle/Lifecycle

你可能感兴趣的:(Android官方架构组件之LiveData + ViewModel + Room 源码分析一)