亲宝软件园·资讯

展开

Android 自定义Livedata使用示例解析

流浪汉kylin 人气:0

前言

我们在开发中在使用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,主要分为两个步骤:

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。

加载全部内容

相关教程
猜你喜欢
用户评论