首頁 > 軟體

Android 自定義Livedata使用範例解析

2022-12-07 14:00:54

前言

我們在開發中在使用MVVM的情況下經常會配合livedata來達到快速開發的效果,但是一般都是在activity或者fragment中去使用,我今天想介紹一種自定義的方式,如果你有複雜的自定義View或者某些場景,也可以使用livedata來達到一個很不錯的效果。

Livedata分析

我們平時使用livedata都會在activity或者fragment中使用,配合 Lifecycle就不用管理生命週期什麼的了,所以一般以activity或fragment作為view層(當然service內也有相應的封裝)。

viewmodel層,繼承lifecycler的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
        }) 

一般來說就這樣寫嘛,也不用考慮登出什麼的,它自己內部幫你實現,很方便,but 也只能在activity或者fragment中能這樣寫

假如在view中這樣寫,傳this的地方會報錯,為什麼呢,我們可以看看view層的兩個this傳的是什麼。
建立ViewModelProvider時傳

public ViewModelProvider(@NonNull ViewModelStoreOwner owner) 

呼叫observe方法時傳

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

可以看到一個是ViewModelStoreOwner,另一個是LifecycleOwner,並不是同一個東西

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內部是怎麼封裝的

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

看介面的實現

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

看到內部是有參照一個ViewModelStore物件
在onDestroy時

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

可以看出實現ViewModelStoreOwner介面就是持有ViewModelStore物件,並保證它的建立和銷燬,而它的內部會持有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();
    }
}

那這個ViewModelStore在哪裡使用呢,我們看到FragmentActivity這裡只做了建立和銷燬,並沒有執行put和get方法,我們深入去看可以發現put/get是在ViewModelProvider中呼叫。這也對應了我們最初的初始化ViewModel的方法

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

所以很容易能看出ViewModelStore就是用來管理viewmodel的。
接下來我們看LifecycleOwner,在activity的實現這個介面的方法

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

看得出返回LifecycleRegistry物件,LifecycleRegistry就是Lifecycle的實現類,在Activity中存在呼叫方法

// 有很多地方有調addObserver方法
getLifecycle().addObserver(new LifecycleEventObserver() {......})
// 在這裡調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);
    }

看得出它們最終都是呼叫moveToState,呼叫handleLifecycleEvent只是為了把 Lifecycle.Event轉成State

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

Lifecycle的程式碼就不分析了,這邊主要講Livedata。
同樣能看出FragmentActivity有呼叫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);
    }

再看看另一個LifecycleOwner的實現,Service,這個Service叫LifecycleService

public class LifecycleService extends Service implements LifecycleOwner

它內部參照一個ServiceLifecycleDispatcher物件,而這個物件內部參照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;
            }
        }
    }

在外層呼叫

 @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();
    }

那麼我們得出一個結論,要實現LifecycleOwner,主要就是自己去使用handleLifecycleEvent方法去設定生命週期。

那麼這裡有個問題,如果我有個Service繼承LifecycleService,它能直接快速的使用Livedata嗎,當然不能,因為LifecycleService只實現了LifecycleOwner,並沒有實現ViewModelStoreOwner

自定義Livedata

按照上面Activity的原始碼,我們知道,要實現Livedata,主要分為兩個步驟:

  • 1. 實現ViewModelStoreOwner並完成ViewModelStore的建立和銷燬
  • 2. 實現LifecycleOwner並手動設定生命週期其實現在網上也有很多人講在自定義View上使用Livedata,我這裡就做點不同的,我在window上去實現,其實原理都是一樣的。
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層中實現livedata功能。

總結

自定義livedata其實沒有太大的難度,這是一個開發的過程,你想在一些地方去使用官方封裝好的框架,可以先去看看它是怎麼做的,再自己進行一個二次封裝,就能實現那麼一個效果,比如這裡的自定義View或者Window使用Livadata。

以上就是Android 自定義Livedata使用範例解析的詳細內容,更多關於Android 自定義Livedata的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com