简体   繁体   English

旋转活动时如何不破坏 ViewModel

[英]How ViewModel is not get destroyed when activity is rotated

I am curious to know how a ViewModel survives when Activity gets rotated because of that it destroyed and recreated again.我很想知道当 Activity 被旋转时 ViewModel 是如何存活的,因为它被销毁并再次重新创建。 Logically If we see then ViewModel gets destroyed if the activity which is responsible to create a ViewModel gets destroyed.从逻辑上讲,如果我们看到,如果负责创建 ViewModel 的活动被销毁,ViewModel 就会被销毁。 And while we rotating the device the Activity is destroying.当我们旋转设备时,Activity 正在破坏。

How the ViewModel knows that Activity is completely finished so that I can destroy myself? ViewModel 如何知道 Activity 已完全完成以便我可以销毁自己? Because onDestroy also being called several times if the device rotated, So how ViewModel's onCleared method triggered when activity completely destroyed?因为如果设备旋转,onDestroy 也会被调用多次,那么当 Activity 完全销毁时,ViewModel 的 onCleared 方法是如何触发的呢?

Theory -> There is a hashmap of type HashMap<String, ViewModel> in ViewModelStore (you can call getViewModelStore() from your activity to get it) which stores the ViewModel state and its used to get existing viewModel in next onCreate, and thats how ViewModel survives configuration change.理论 -> ViewModelStore 中有一个类型为HashMap<String, ViewModel>的 hashmap(您可以从您的活动中调用 getViewModelStore() 来获取它),它存储 ViewModel state,它用于在下一个 onCreate 中获取现有的 viewModel,这就是如何ViewModel 在配置更改后仍然存在。 So ViewModel is destroyed when its clear() method is called and viewModelStore's clear method internally calls viewModel's clear.所以ViewModel在它的clear()方法被调用时被销毁,viewModelStore的clear方法在内部调用viewModel的clear。

To answer your question, there exists an internal check, which avoids this clear method getting called in onDestroy if its because of configuration change.为了回答你的问题,存在一个内部检查,如果它是因为配置更改,它可以避免在 onDestroy 中调用这个明确的方法。

reference from ComponentActivity source code ->来自 ComponentActivity 源代码的引用 ->

 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();
                    }
                }
            }
        });

Note the if check of isChangingConfiguration, thats why clear is not called on configuration change注意 isChangingConfiguration 的 if 检查,这就是为什么在配置更改时不调用 clear 的原因

Again from source code isChangingConfigurations()再次来自源代码isChangingConfigurations()

Returns: If the activity is being torn down in order to be recreated with a new configuration, returns true;返回:如果正在拆除活动以便使用新配置重新创建,则返回 true; else returns false.否则返回假。

ViewModels are lifecycle aware which means that when you create a view model you pass the LifecycleOwner to the VM. ViewModel 具有生命周期感知能力,这意味着当您创建视图模型时,您将LifecycleOwner传递给 VM。 This helps the View Model to get the state of the context(Be it activity, fragment etc).这有助于视图模型获取上下文的状态(无论是活动、片段等)。 This allows the view model to broadcast the changes to its observers only when the state is active.这允许视图模型仅在状态处于活动状态时将更改广播给其观察者。

Refer to the below links for more clarity请参阅以下链接以获得更清晰的信息

https://developer.android.com/topic/libraries/architecture/lifecycle#lco https://codelabs.developers.google.com/codelabs/android-lifecycles/#4 https://developer.android.com/topic/libraries/architecture/lifecycle#lco https://codelabs.developers.google.com/codelabs/android-lifecycles/#4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM