Jetpack ViewModel组件其他使用方式-之四

前言

前面介绍ViewModel时,说到ViewModel常与livedata联合使用;但是ViewModel不单单是为了livedata而创建的,它可以帮助我们保存UI相关的数据,维护与UI一直的生命周期并排除config change造成的影响;这里再介绍一种ViewModel的使用场景;如sdk中要实现无UI接口,你不知道具体的接入方的逻辑是怎么样的,比如要通过一个flag来控制不同的逻辑,但是因为接入方的界面不是你实现的,你怎么添加这个flag呢; 就是通过ViewModel,实际上将你的flag标志和接入方的实例对象绑定起来;同时前面说过HolderFragment的思路是值得借鉴的,我们在本文中也会看看如何使用

ViewModel使用

创建ViewModel

public class MyViewModel extends ViewModel {
    private boolean mflag;

    public boolean isflag() {
        return mflag;
    }

    public void setFlag(boolean mFlag) {
        this.mflag = mFlag;
    }
} 

将ViewModel实例与接入方界面绑定

MyViewModel myViewModel = ViewModelProviders.of(activity).get(MyViewModel.class);
MyViewModel myViewModel = ViewModelProviders.of(fragment).get(MyViewModel.class);

这样就可以通过创建viewmodel示例对象来操作与activity/fragment相关的flag;

局限性

但是这种方法是有局限性的;我们看下ViewModelProviders, ViewModelStores的接口

/**
     * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity
     * is alive. More detailed explanation is in {@link ViewModel}.
     * 

* It uses {@link ViewModelProvider.AndroidViewModelFactory} to instantiate new ViewModels. * * @param activity an activity, in whose scope ViewModels should be retained * @return a ViewModelProvider instance */ @NonNull @MainThread public static ViewModelProvider of(@NonNull FragmentActivity activity) { return of(activity, null); } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given * {@code fragment} is alive. More detailed explanation is in {@link ViewModel}. *

* It uses the given {@link Factory} to instantiate new ViewModels. * * @param fragment a fragment, in whose scope ViewModels should be retained * @param factory a {@code Factory} to instantiate new ViewModels * @return a ViewModelProvider instance */ @NonNull @MainThread public static ViewModelProvider of(@NonNull Fragment fragment, @Nullable Factory factory) { Application application = checkApplication(checkActivity(fragment)); if (factory == null) { factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application); } return new ViewModelProvider(ViewModelStores.of(fragment), factory); } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity * is alive. More detailed explanation is in {@link ViewModel}. *

* It uses the given {@link Factory} to instantiate new ViewModels. * * @param activity an activity, in whose scope ViewModels should be retained * @param factory a {@code Factory} to instantiate new ViewModels * @return a ViewModelProvider instance */ @NonNull @MainThread public static ViewModelProvider of(@NonNull FragmentActivity activity, @Nullable Factory factory) { Application application = checkApplication(activity); if (factory == null) { factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application); } return new ViewModelProvider(ViewModelStores.of(activity), factory); }

    /**
     * Returns the {@link ViewModelStore} of the given activity.
     *
     * @param activity an activity whose {@code ViewModelStore} is requested
     * @return a {@code ViewModelStore}
     */
    @NonNull
    @MainThread
    public static ViewModelStore of(@NonNull FragmentActivity activity) {
        if (activity instanceof ViewModelStoreOwner) {
            return ((ViewModelStoreOwner) activity).getViewModelStore();
        }
        return holderFragmentFor(activity).getViewModelStore();
    }

    /**
     * Returns the {@link ViewModelStore} of the given fragment.
     *
     * @param fragment a fragment whose {@code ViewModelStore} is requested
     * @return a {@code ViewModelStore}
     */
    @NonNull
    @MainThread
    public static ViewModelStore of(@NonNull Fragment fragment) {
        if (fragment instanceof ViewModelStoreOwner) {
            return ((ViewModelStoreOwner) fragment).getViewModelStore();
        }
        return holderFragmentFor(fragment).getViewModelStore();
    }

我们看到传入的参数只支持support的activity/fragment; 前面我们也分析过HolderFragment,说明了其是为了向前适配的, 我们看下能否使用HolderFragment呢?

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class HolderFragment extends Fragment implements ViewModelStoreOwner

很可惜是不行的,这个类里面的接口都是隐藏的;

这个就比较奇怪了,明明底层已经做了适配,但不把上层接口暴露出来;这个底层有什么用呢?

原因: 适配是适配了androidx的support activity/fragment;而不是normal Activity/Fragment(android.app.activity)

参考:
Before androidx FragmentActivity.java
androidx FragmentActivity.java

借鉴HolderFragment

虽然不明白google为什么没有为normal activity提供接口;但是既然没有开放接口,我们也只能另想办法了; 我们可以写一个类HolderFragment,然后将其依赖到接入方的normal activity/fragment;然后再通过其得到对应的ViewModel中保存的flag; 如下:

public class HolderFragmentForNormalUI extends Fragment implements ViewModelStoreOwner {
    private static final String LOG_TAG = "ViewModelStores";

    private static final HolderFragmentForNormalUI.HolderFragmentManager sHolderFragmentManager = new HolderFragmentForNormalUI.HolderFragmentManager();

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static final String HOLDER_TAG =
            "com.bytedance.ttgame.sdk.module.account.utils.HolderFragmentForNormalUI";

    private ViewModelStore mViewModelStore = new ViewModelStore();

    public HolderFragmentForNormalUI() {
        setRetainInstance(true);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sHolderFragmentManager.holderFragmentCreated(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mViewModelStore.clear();
    }

    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        return mViewModelStore;
    }

    public static HolderFragmentForNormalUI holderFragmentFor(Activity activity) {
        return sHolderFragmentManager.holderFragmentFor(activity);
    }

    public static HolderFragmentForNormalUI holderFragmentFor(Fragment fragment) {
        return sHolderFragmentManager.holderFragmentFor(fragment);
    }

    @SuppressWarnings("WeakerAccess")
    static class HolderFragmentManager {
        private Map mNotCommittedActivityHolders = new HashMap<>();
        private Map mNotCommittedFragmentHolders = new HashMap<>();

        private Application.ActivityLifecycleCallbacks mActivityCallbacks =
                new EmptyActivityLifecycleCallbacksForNormalUI() {
                    @Override
                    public void onActivityDestroyed(Activity activity) {
                        HolderFragmentForNormalUI fragment = mNotCommittedActivityHolders.remove(activity);
                        if (fragment != null) {
                            Log.e(LOG_TAG, "Failed to save a ViewModel for " + activity);
                        }
                    }
                };

        private boolean mActivityCallbacksIsAdded = false;

        void holderFragmentCreated(Fragment holderFragment) {
            mNotCommittedActivityHolders.remove(holderFragment.getActivity());
        }

        private static HolderFragmentForNormalUI findHolderFragment(FragmentManager manager) {
            if (manager.isDestroyed()) {
                throw new IllegalStateException("Can't access ViewModels from onDestroy");
            }

            Fragment fragmentByTag = manager.findFragmentByTag(HOLDER_TAG);
            if (fragmentByTag != null && !(fragmentByTag instanceof HolderFragmentForNormalUI)) {
                throw new IllegalStateException("Unexpected "
                        + "fragment instance was returned by HOLDER_TAG");
            }
            return (HolderFragmentForNormalUI) fragmentByTag;
        }

        private static HolderFragmentForNormalUI createHolderFragment(FragmentManager fragmentManager) {
            HolderFragmentForNormalUI holder = new HolderFragmentForNormalUI();
            fragmentManager.beginTransaction().add(holder, HOLDER_TAG).commitAllowingStateLoss();
            return holder;
        }

        HolderFragmentForNormalUI holderFragmentFor(Activity activity) {
            FragmentManager fm = activity.getFragmentManager();
            HolderFragmentForNormalUI holder = findHolderFragment(fm);
            if (holder != null) {
                return holder;
            }
            holder = mNotCommittedActivityHolders.get(activity);
            if (holder != null) {
                return holder;
            }

            if (!mActivityCallbacksIsAdded) {
                mActivityCallbacksIsAdded = true;
                activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks);
            }
            holder = createHolderFragment(fm);
            mNotCommittedActivityHolders.put(activity, holder);
            return holder;
        }

        HolderFragmentForNormalUI holderFragmentFor(Fragment parentFragment) {
            FragmentManager fm = parentFragment.getChildFragmentManager();
            HolderFragmentForNormalUI holder = findHolderFragment(fm);
            if (holder != null) {
                return holder;
            }
            holder = createHolderFragment(fm);
            return holder;
        }
    }

使用方式(activity为android.app.Activity)

MyViewModel myViewModel = new ViewModelProvider(HolderFragmentForNormalUI.holderFragmentFor(activity).getViewModelStore(),
                    ViewModelProvider.AndroidViewModelFactory.getInstance(activity.getApplication())).get(SendCodeViewModel.class);

总结

ViewModel与activity/fragment依赖的关系可以用来给无法操作的界面添加相应属性,标志位等;适用于我们抽取无UI接口时,有些地方需要与界面有耦合关系的情况(当然理想情况下这是不合理的,可惜现实往往并不总能尽如人意); jectpack组件的使用方式还有很多,这都有待于我们探索;

你可能感兴趣的:(Jetpack ViewModel组件其他使用方式-之四)