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}.
     * <p>
     * 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}.
     * <p>
     * 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}.
     * <p>
     * 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<Activity, HolderFragmentForNormalUI> mNotCommittedActivityHolders = new HashMap<>();
        private Map<Fragment, HolderFragmentForNormalUI> 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组件的使用方式还有很多,这都有待于我们探索;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,776评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,527评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,361评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,430评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,511评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,544评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,561评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,315评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,763评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,070评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,235评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,911评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,554评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,173评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,424评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,106评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,103评论 2 352

推荐阅读更多精彩内容