欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LifecycleModel 分享

程序员文章站 2022-03-18 10:57:47
这里写目录标题源码地址使用粘贴使用的代码自定义 LifecycleModel创建收发源码地址源码地址:https://github.com/JessYanCoding/LifecycleModel作者解读:https://juejin.im/post/6844903529094578189使用一直都想用ViewModel,但是又不想用MVVM,偶然看到了大神的实现,使用简单而且方便注意最好下载代码,因为源码没有更新到 AndroidX,下载下来改改就好,主要是思想哦!粘贴使用的代码自定义 L...

源码地址

源码地址:https://github.com/JessYanCoding/LifecycleModel
作者解读:https://juejin.im/post/6844903529094578189

使用

一直都想用ViewModel,但是又不想用MVVM,偶然看到了大神的实现,使用简单而且方便
注意最好下载代码,因为源码没有更新到 AndroidX,下载下来改改就好,主要是思想哦!

粘贴使用的代码

自定义 LifecycleModel

public class UserLifecycleModel implements LifecycleModel {

    private Subject<String> mSubject = PublishSubject.create();

    public void doAction(String s) {
        mSubject.onNext(s);
    }

    public void addAction(Consumer<String> consumer) {
        mSubject.subscribe(consumer);
    }

    @Override
    public void onCleared() {

    }

}

创建

LifecycleModelProviders.of(this).put(UserLifecycleModel.class.getName(), new UserLifecycleModel());

        UserLifecycleModel lifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName());
        lifecycleModel.addAction(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                // Update the UI.
                Log.d("AFragment", s);
            }

        });

        UserLifecycleModel lifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName());
        lifecycleModel.doAction("JessYan");

源码类分析

/*
 * Copyright 2017 JessYan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package me.jessyan.lifecyclemodel;

import android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
import android.os.Bundle;

import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import java.util.HashMap;
import java.util.Map;

/**
 * @hide 此类为实现 {@link LifecycleModel} 的核心类
 * <p>
 * Created by JessYan on 21/11/2017 16:57
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class HolderFragment extends Fragment {
    private static final String LOG_TAG = "LifecycleModelStores";

    private static final HolderFragmentManager sHolderFragmentManager = new HolderFragmentManager();

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static final String HOLDER_TAG =
            "me.jessyan.lifecyclemodel.state.StateProviderHolderFragment";

    private final LifecycleModelStore mLifecycleModelStore = new LifecycleModelStore();

    public HolderFragment() {
        setRetainInstance(true);//Fragment 在 Activity 重建的时候存活下来
    }

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

    public LifecycleModelStore getLifecycleModelStore() {
        return mLifecycleModelStore;
    }

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static HolderFragment holderFragmentFor(FragmentActivity activity) {
        return sHolderFragmentManager.holderFragmentFor(activity);
    }

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static HolderFragment holderFragmentFor(Fragment fragment) {
        return sHolderFragmentManager.holderFragmentFor(fragment);
    }

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

        //Activity销毁的时候移除掉
        private ActivityLifecycleCallbacks mActivityCallbacks =
                new EmptyActivityLifecycleCallbacks() {
                    @Override
                    public void onActivityDestroyed(Activity activity) {
                        HolderFragment fragment = mNotCommittedActivityHolders.remove(activity);
                        if (fragment != null) {
                            Log.e(LOG_TAG, "Failed to save a LifecycleModel for " + activity);
                        }
                    }
                };

        private boolean mActivityCallbacksIsAdded = false;

        //Fragment销毁的时候移除掉
        private FragmentManager.FragmentLifecycleCallbacks mParentDestroyedCallback =
                new FragmentManager.FragmentLifecycleCallbacks() {
                    @Override
                    public void onFragmentDestroyed(FragmentManager fm, Fragment parentFragment) {
                        super.onFragmentDestroyed(fm, parentFragment);
                        HolderFragment fragment = mNotCommittedFragmentHolders.remove(
                                parentFragment);
                        if (fragment != null) {
                            Log.e(LOG_TAG, "Failed to save a LifecycleModel for " + parentFragment);
                        }
                    }
                };

        void holderFragmentCreated(Fragment holderFragment) {
            Fragment parentFragment = holderFragment.getParentFragment();//getParentFragment() 方法可以获取到fragment的宿主fragment.
            if (parentFragment != null) {
                mNotCommittedFragmentHolders.remove(parentFragment);//移除 Fragment KEY
                parentFragment.getFragmentManager().unregisterFragmentLifecycleCallbacks(
                        mParentDestroyedCallback);
            } else {
                mNotCommittedActivityHolders.remove(holderFragment.getActivity());//移除 Activity KEY
            }
        }

        //通过 HOLDER_TAG 找到我们的 Fragment
        private static HolderFragment findHolderFragment(FragmentManager manager) {
            if (manager.isDestroyed()) {
                throw new IllegalStateException("Can't access LifecycleModels from onDestroy");
            }

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

        //创建 Fragment 携带 HOLDER_TAG ,提交
        private static HolderFragment createHolderFragment(FragmentManager fragmentManager) {
            HolderFragment holder = new HolderFragment();
            fragmentManager.beginTransaction().add(holder, HOLDER_TAG).commitAllowingStateLoss();
            return holder;
        }

        //通过 FragmentActivity 找到我们的 记录的 Fragment
        HolderFragment holderFragmentFor(FragmentActivity activity) {
            FragmentManager fm = activity.getSupportFragmentManager();
            HolderFragment holder = findHolderFragment(fm);//找到 Fragment
            if (holder != null) {
                return holder;
            }
            holder = mNotCommittedActivityHolders.get(activity);//看看列表有没有 Fragment
            if (holder != null) {
                return holder;
            }

            if (!mActivityCallbacksIsAdded) { //没有加入 Fragment
                mActivityCallbacksIsAdded = true;
                activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks);
            }
            holder = createHolderFragment(fm);//创建 (带TAG)
            mNotCommittedActivityHolders.put(activity, holder);// 加入列表
            return holder;//返回
        }

        //通过 Fragment 找到我们的 记录的 Fragment
        HolderFragment holderFragmentFor(Fragment parentFragment) {
            FragmentManager fm = parentFragment.getChildFragmentManager();
            HolderFragment holder = findHolderFragment(fm);
            if (holder != null) {
                return holder;
            }
            holder = mNotCommittedFragmentHolders.get(parentFragment);
            if (holder != null) {
                return holder;
            }

            parentFragment.getFragmentManager()
                    .registerFragmentLifecycleCallbacks(mParentDestroyedCallback, false);
            holder = createHolderFragment(fm);
            mNotCommittedFragmentHolders.put(parentFragment, holder);
            return holder;
        }
    }
}

主要是利用 Fragment 的重建保存数据。

本文地址:https://blog.csdn.net/weixin_35691921/article/details/109614661