Andriod ViewModel

ViewModel

概念

负责存储Activity Fragment一些信息

viewModel 都放在viewModelStore里面去了

CompenentActivity 继承关系

ViewModelStoreOwner来源的地方 解释一个Activity只有一个viewModelStoreOwer

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        ContextAware,
        LifecycleOwner,
        ViewModelStoreOwner,
        HasDefaultViewModelProviderFactory,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner,
        ActivityResultRegistryOwner,
        ActivityResultCaller,
        OnConfigurationChangedProvider,
        OnTrimMemoryProvider,
        OnNewIntentProvider,
        OnMultiWindowModeChangedProvider,
        OnPictureInPictureModeChangedProvider,
        MenuHost</span></span>

加入

Activity 绑定ViewModel

@Override
public LoraPageViewModel getViewModel() {
    return new ViewModelProvider(getActivity(),
            new LoraPageViewModel.LoraPageViewModelFactory())
            .get(LoraPageViewModel.class);
}

//无参构造方法

gdOperationViewModel = new ViewModelProvider(this).get(GdOperationViewModel.class);

viewModelProvider 构造方法

 public constructor(owner: ViewModelStoreOwner, factory: Factory) : this(
        owner.viewModelStore,
        factory,
        defaultCreationExtras(owner)
    )

get store.put(key, it)

@Suppress("UNCHECKED_CAST")
    @MainThread
    public open operator fun <T : ViewModel> get(key: String, modelClass: Class<T>): T {
        val viewModel = store[key]  //store is viewModelStore
        if (modelClass.isInstance(viewModel)) {
            (factory as? OnRequeryFactory)?.onRequery(viewModel)
            return viewModel as T
        } else {
            @Suppress("ControlFlowWithEmptyBody")
            if (viewModel != null) {
                // TODO: log a warning.
            }
        }
        val extras = MutableCreationExtras(defaultCreationExtras)
        extras[VIEW_MODEL_KEY] = key
        // AGP has some desugaring issues associated with compileOnly dependencies so we need to
        // fall back to the other create method to keep from crashing.
        return try {
            factory.create(modelClass, extras)
        } catch (e: AbstractMethodError) {
            factory.create(modelClass)
        }.also { store.put(key, it) }// it is viewModel
    }   

共用

一个Activity一个viewModelStore 如果是同一个AViewModel 在同一个Activity get两次会从map里面取

ViewModelStoreOwner 被Activity Fragment实现了

AFragment 在AActivity里面 都by viewModel 这两个viewModel不一样

移除

ComponentActivity

  //onDestory 移除ViewModel
      public ComponentActivity() {
        Lifecycle lifecycle = getLifecycle();
        //noinspection ConstantConditions
        if (lifecycle == null) {
            throw new IllegalStateException("getLifecycle() returned null in ComponentActivity's "
                    + "constructor. Please make sure you are lazily constructing your Lifecycle "
                    + "in the first call to getLifecycle() rather than relying on field "
                    + "initialization.");
        }
        getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source,
                    @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    // Clear out the available context
                    mContextAwareHelper.clearAvailableContext();
                    // And clear the ViewModelStore
                    if (!isChangingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
        });
   
        mSavedStateRegistryController.performAttach();
        enableSavedStateHandles(this);
​
    
    
    }

Fragment Activity ViewModel

Fragment ComponentActivity 都是继承ViewModelStoreOwer

public class Fragment implements ViewModelStoreOwner

public class ComponentActivity implements ViewModelStoreOwner,

所以Activity下的Fragment可能用的不是一个ViewModelStoreOwner 主要看使用ViewModelProvider 传参

如果传getActivity()就和Activity共用一个ViewModelStore 如果传this就是自己单独一个ViewModelStore

@Override
public LightValueViewModel getViewModel() {
    RequestDevBean requestDevBean = adjustLightPageData.coverToRequestDev(QueryLightEnum.ONE.getType());
    return new ViewModelProvider(this,
            new LightValueViewModel.MapLightValueViewModelFactory(requestDevBean))
            .get(LightValueViewModel.class);
}
public interface ViewModelStoreOwner {
    /**
     * Returns owned {@link ViewModelStore}
     *
     * @return a {@code ViewModelStore}
     */
    @NonNull
    ViewModelStore getViewModelStore();
}

ViewModelStore

public final void clear() {
    for (ViewModel vm : mMap.values()) {
        vm.clear();
    }
    mMap.clear();//mMap 是HashMap
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值