自定義Livedata

雖然Livedata已經(jīng)有點(diǎn)過時(shí),但是碰到一些有意思的情況我認(rèn)為還是值得記錄一下。

一. Activity/Fragment/Service中封裝的Livedata

我們平時(shí)使用livedata都會(huì)在activity或者fragment中使用,配合 Lifecycle就不用管理生命周期什么的了,所以一般以activity或fragment作為view層(當(dāng)然service內(nèi)也有相應(yīng)的封裝)。
viewmodel層,繼承l(wèi)ifecycler的ViewModel

var data : MutableLiveData<Int> = MutableLiveData()

fun test(){
  data.value = 1
}

view層

var viewmodel = ViewModelProvider(this).get(TestViewModel::class.java)
viewmodel?. data?.observe(this, Observer {
            // todo
        }) 

一般來說就這樣寫嘛,也不用考慮注銷什么的,它自己內(nèi)部幫你實(shí)現(xiàn),很方便,but 也只能在activity或者fragment中能這樣寫

假如在view中這樣寫,傳this的地方會(huì)報(bào)錯(cuò),為什么呢,我們可以看看view層的兩個(gè)this傳的是什么。
創(chuàng)建ViewModelProvider時(shí)傳

public ViewModelProvider(@NonNull ViewModelStoreOwner owner) 

調(diào)用observe方法時(shí)傳

public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer)

可以看到一個(gè)是ViewModelStoreOwner,另一個(gè)是LifecycleOwner,并不是同一個(gè)東西

public interface ViewModelStoreOwner {
    /**
     * Returns owned {@link ViewModelStore}
     *
     * @return a {@code ViewModelStore}
     */
    @NonNull
    ViewModelStore getViewModelStore();
}
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

我們看看Activity內(nèi)部是怎么封裝的

public class FragmentActivity extends ComponentActivity implements
        ViewModelStoreOwner,
        ActivityCompat.OnRequestPermissionsResultCallback,
        ActivityCompat.RequestPermissionsRequestCodeValidator 
public class ComponentActivity extends Activity
        implements LifecycleOwner, KeyEventDispatcher.Component 

看接口的實(shí)現(xiàn)

    public ViewModelStore getViewModelStore() {
        ......
        if (mViewModelStore == null) {
            ......
            if (mViewModelStore == null) {
                mViewModelStore = new ViewModelStore();
            }
        }
        return mViewModelStore;
    }

看到內(nèi)部是有引用一個(gè)ViewModelStore對(duì)象
在onDestroy時(shí)

    protected void onDestroy() {
        super.onDestroy();
        if (mViewModelStore != null && !isChangingConfigurations()) {
            mViewModelStore.clear();
        }
        ......
    }

可以看出實(shí)現(xiàn)ViewModelStoreOwner接口就是持有ViewModelStore對(duì)象,并保證它的創(chuàng)建和銷毀,而它的內(nèi)部會(huì)持有viewmodel

public class ViewModelStore {

    private final HashMap<String, ViewModel> mMap = new HashMap<>();

    final void put(String key, ViewModel viewModel) {
        ViewModel oldViewModel = mMap.put(key, viewModel);
        if (oldViewModel != null) {
            oldViewModel.onCleared();
        }
    }

    final ViewModel get(String key) {
        return mMap.get(key);
    }

    /**
     *  Clears internal storage and notifies ViewModels that they are no longer used.
     */
    public final void clear() {
        for (ViewModel vm : mMap.values()) {
            vm.onCleared();
        }
        mMap.clear();
    }
}

那這個(gè)ViewModelStore在哪里使用呢,我們看到FragmentActivity這里只做了創(chuàng)建和銷毀,并沒有執(zhí)行put和get方法,我們深入去看可以發(fā)現(xiàn)put/get是在ViewModelProvider中調(diào)用。這也對(duì)應(yīng)了我們最初的初始化ViewModel的方法

var viewmodel = ViewModelProvider(this).get(TestViewModel::class.java)

所以很容易能看出ViewModelStore就是用來管理viewmodel的。
接下來我們看LifecycleOwner,在activity的實(shí)現(xiàn)這個(gè)接口的方法

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

看得出返回LifecycleRegistry對(duì)象,LifecycleRegistry就是Lifecycle的實(shí)現(xiàn)類,在Activity中存在調(diào)用方法

// 有很多地方有調(diào)addObserver方法
getLifecycle().addObserver(new LifecycleEventObserver() {......})
// 在這里調(diào)setCurrentState方法
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        Lifecycle lifecycle = getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);
        }
        super.onSaveInstanceState(outState);
        mSavedStateRegistryController.performSave(outState);
    }

值得注意的是LifecycleRegistry中的setCurrentState方法和handleLifecycleEvent方法

    @MainThread
    public void setCurrentState(@NonNull State state) {
        moveToState(state);
    }

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

看得出它們最終都是調(diào)用moveToState,調(diào)用handleLifecycleEvent只是為了把 Lifecycle.Event轉(zhuǎn)成State

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        ......
    }

Lifecycle的代碼就不分析了,這邊主要講Livedata。
同樣能看出FragmentActivity有調(diào)用handleLifecycleEvent

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        mFragments.dispatchCreate();
    }

   @Override
    protected void onStart() {
        ......
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
        mFragments.dispatchStart();
    }

    protected void onResumeFragments() {
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
        mFragments.dispatchResume();
    }

    @Override
    protected void onStop() {
        ......
        mFragments.dispatchStop();
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFragments.dispatchDestroy();
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
    }

再看看另一個(gè)LifecycleOwner的實(shí)現(xiàn),Service,這個(gè)Service叫LifecycleService

public class LifecycleService extends Service implements LifecycleOwner

它內(nèi)部引用一個(gè)ServiceLifecycleDispatcher對(duì)象,而這個(gè)對(duì)象內(nèi)部引用LifecycleRegistry。


    /**
     * Must be a first call in {@link Service#onCreate()} method, even before super.onCreate call.
     */
    public void onServicePreSuperOnCreate() {
        postDispatchRunnable(Lifecycle.Event.ON_CREATE);
    }

    /**
     * Must be a first call in {@link Service#onBind(Intent)} method, even before super.onBind
     * call.
     */
    public void onServicePreSuperOnBind() {
        postDispatchRunnable(Lifecycle.Event.ON_START);
    }

    /**
     * Must be a first call in {@link Service#onStart(Intent, int)} or
     * {@link Service#onStartCommand(Intent, int, int)} methods, even before
     * a corresponding super call.
     */
    public void onServicePreSuperOnStart() {
        postDispatchRunnable(Lifecycle.Event.ON_START);
    }

    /**
     * Must be a first call in {@link Service#onDestroy()} method, even before super.OnDestroy
     * call.
     */
    public void onServicePreSuperOnDestroy() {
        postDispatchRunnable(Lifecycle.Event.ON_STOP);
        postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
    }

    @NonNull
    public Lifecycle getLifecycle() {
        return mRegistry;
    }

    static class DispatchRunnable implements Runnable {
        private final LifecycleRegistry mRegistry;
        final Lifecycle.Event mEvent;
        private boolean mWasExecuted = false;

        DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) {
            mRegistry = registry;
            mEvent = event;
        }

        @Override
        public void run() {
            if (!mWasExecuted) {
                mRegistry.handleLifecycleEvent(mEvent);
                mWasExecuted = true;
            }
        }
    }

在外層調(diào)用

 @CallSuper
    @Override
    public void onCreate() {
        mDispatcher.onServicePreSuperOnCreate();
        super.onCreate();
    }

    @CallSuper
    @Nullable
    @Override
    public IBinder onBind(@NonNull Intent intent) {
        mDispatcher.onServicePreSuperOnBind();
        return null;
    }

    @SuppressWarnings("deprecation")
    @CallSuper
    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        mDispatcher.onServicePreSuperOnStart();
        super.onStart(intent, startId);
    }

    // this method is added only to annotate it with @CallSuper.
    // In usual service super.onStartCommand is no-op, but in LifecycleService
    // it results in mDispatcher.onServicePreSuperOnStart() call, because
    // super.onStartCommand calls onStart().
    @CallSuper
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @CallSuper
    @Override
    public void onDestroy() {
        mDispatcher.onServicePreSuperOnDestroy();
        super.onDestroy();
    }

    @Override
    @NonNull
    public Lifecycle getLifecycle() {
        return mDispatcher.getLifecycle();
    }

那么我們得出一個(gè)結(jié)論,要實(shí)現(xiàn)LifecycleOwner,主要就是自己去使用handleLifecycleEvent方法去設(shè)置生命周期。

那么這里有個(gè)問題,如果我有個(gè)Service繼承LifecycleService,它能直接快速的使用Livedata嗎,當(dāng)然不能,因?yàn)長(zhǎng)ifecycleService只實(shí)現(xiàn)了LifecycleOwner,并沒有實(shí)現(xiàn)ViewModelStoreOwner

二. 使用自定義Livedata

按照上面Activity的源碼,我們知道,要實(shí)現(xiàn)Livedata,主要分為兩個(gè)步驟:
1. 實(shí)現(xiàn)ViewModelStoreOwner并完成ViewModelStore的創(chuàng)建和銷毀
2. 實(shí)現(xiàn)LifecycleOwner并手動(dòng)設(shè)置生命周期
其實(shí)現(xiàn)在網(wǎng)上也有很多人講在自定義View上使用Livedata,我這里就做點(diǎn)不同的,我在window上去實(shí)現(xiàn),其實(shí)原理都是一樣的。

class MyWindow internal constructor(val context: Context) : AbstractWindow(), LifecycleOwner,
    ViewModelStoreOwner {
    
    private var mViewModel : MyViewModel? = null
    private var mViewModelStore: ViewModelStore ?= null
    private val mRegistry = LifecycleRegistry(this)

  fun init(){
  // todo一些初始化操作
   mRegistry.currentState = Lifecycle.State.CREATED
   mViewModel = ViewModelProvider(this).get(MyViewModel::class.java)
   mViewModel?.data?.observe(this, Observer {
            ......
        })
  }

  fun show(){
    mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
    mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
    mWindowManager.addView(mView, getLayoutParams());
  }

  fun close(){
    mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
    mWindowManager.removeViewImmediate(mView);
  }

    override fun getLifecycle(): Lifecycle {
        return mRegistry
    }

    override fun getViewModelStore(): ViewModelStore {
        if (mViewModelStore == null){
            mViewModelStore = ViewModelStore()
        }
        return mViewModelStore!!
    }

    fun onDestroy(){
     mRegistry?.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
     mViewModelStore?.clear()
    }

這樣就能在非activity/fragment的view層中實(shí)現(xiàn)livedata功能。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容