Android 面试之—— ViewModel 总结篇,2024年最新怒肝三个月啃完这110道面试题

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip204888 (备注Android)
img

正文

return (T) viewModel;

} else {

//noinspection StatementWithEmptyBody

if (viewModel != null) {

// TODO: log a warning.

}

}

// 使用工厂模式创建 ViewModel 实例

if (mFactory instanceof KeyedFactory) {

viewModel = ((KeyedFactory) mFactory).create(key, modelClass);

} else {

viewModel = mFactory.create(modelClass);

}

// 将创建的 ViewModel 实例放进 mViewModelStore 缓存中

mViewModelStore.put(key, viewModel);

// 返回新创建的 ViewModel 实例

return (T) viewModel;

}

mViewModelStore 是啥?通过 ViewModelProvider 的构造方法知道 mViewModelStore 其实是我们 Activity 里的 mViewModelStore 对象,它在 ComponentActivity 中被声明。 看到了 put 方法,不难猜它内部用了 Map 结构。

public class ViewModelStore {

// 果不其然,内部有一个 HashMap

private final HashMap<String, ViewModel> mMap = new HashMap<>();

final void put(String key, ViewModel viewModel) {

ViewModel oldViewModel = mMap.put(key, viewModel);

if (oldViewModel != null) {

oldViewModel.onCleared();

}

}

// 通过 key 获取 ViewModel 对象

final ViewModel get(String key) {

return mMap.get(key);

}

Set keys() {

return new HashSet<>(mMap.keySet());

}

/**

  • Clears internal storage and notifies ViewModels that they are no longer used.

*/

public final void clear() {

for (ViewModel vm : mMap.values()) {

vm.clear();

}

mMap.clear();

}

}

到这儿正常情况下 ViewModel 的创建流程看完了,似乎没有解决任何问题~ 简单总结:ViewModel 对象存在了 ComponentActivitymViewModelStore 对象中。 第二个问题解决了:ViewModel 的实例缓存到哪儿了

转换思路 mViewModelStore 出现频率这么高,何不看看它是什么时候被创建的呢?

记不记得刚才看 ViewModelProvider 的构造方法时 ,获取 ViewModelStore 对象时,实际调用了 MainActivity#getViewModelStore() ,而 getViewModelStore() 实现在 MainActivity 的父类 ComponentActivity 中。

// ComponentActivity#getViewModelStore()

@Override

public ViewModelStore getViewModelStore() {

if (getApplication() == null) {

throw new IllegalStateException("Your activity is not yet attached to the "

  • “Application instance. You can’t request ViewModel before onCreate call.”);

}

ensureViewModelStore();

return mViewModelStore;

}

在返回 mViewModelStore 对象之前调用了 ensureViewModelStore()

void ensureViewModelStore() {

if (mViewModelStore == null) {

NonConfigurationInstances nc =

(NonConfigurationInstances) getLastNonConfigurationInstance();

if (nc != null) {

// Restore the ViewModelStore from NonConfigurationInstances

mViewModelStore = nc.viewModelStore;

}

if (mViewModelStore == null) {

mViewModelStore = new ViewModelStore();

}

}

}

mViewModelStore == null 调用了 getLastNonConfigurationInstance() 获取 NonConfigurationInstances 对象 nc,当 nc != null 时将 mViewModelStore 赋值为 nc.viewModelStore,最终 viewModelStore == null 时,才会创建 ViewModelStore 实例。

不难发现,之前创建的 viewModelStore 对象被缓存在 NonConfigurationInstances

// 它是 ComponentActivity 的静态内部类

static final class NonConfigurationInstances {

Object custom;

// 果然在这儿

ViewModelStore viewModelStore;

}

NonConfigurationInstances 对象通过 getLastNonConfigurationInstance() 来获取的

// Activity#getLastNonConfigurationInstance

/**

  • Retrieve the non-configuration instance data that was previously

  • returned by {@link #onRetainNonConfigurationInstance()}. This will

  • be available from the initial {@link #onCreate} and

  • {@link #onStart} calls to the new instance, allowing you to extract

  • any useful dynamic state from the previous instance.

  • Note that the data you retrieve here should only be used

  • as an optimization for handling configuration changes. You should always

  • be able to handle getting a null pointer back, and an activity must

  • still be able to restore itself to its previous state (through the

  • normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this

  • function returns null.

  • Note: For most cases you should use the {@link Fragment} API

  • {@link Fragment#setRetainInstance(boolean)} instead; this is also

  • available on older platforms through the Android support libraries.

  • @return the object previously returned by {@link #onRetainNonConfigurationInstance()}

*/

@Nullable

public Object getLastNonConfigurationInstance() {

return mLastNonConfigurationInstances != null

? mLastNonConfigurationInstances.activity : null;

}

好长一段注释,大概意思有几点:

  • onRetainNonConfigurationInstance 方法和 getLastNonConfigurationInstance 是成对出现的,跟 onSaveInstanceState 机制类似,只不过它是仅用作处理配置更改的优化。

  • 返回的是 onRetainNonConfigurationInstance 返回的对象

onRetainNonConfigurationInstance 和 getLastNonConfigurationInstance 的调用时机在本篇文章不做赘述,后续文章会进行解释。

看看 onRetainNonConfigurationInstance 方法

/**

  • 保留所有适当的非配置状态

*/

@Override

@Nullable

@SuppressWarnings(“deprecation”)

public final Object onRetainNonConfigurationInstance() {

// Maintain backward compatibility.

Object custom = onRetainCustomNonConfigurationInstance();

ViewModelStore viewModelStore = mViewModelStore;

// 若 viewModelStore 为空,则尝试从 getLastNonConfigurationInstance() 中获取

if (viewModelStore == null) {

// No one called getViewModelStore(), so see if there was an existing

// ViewModelStore from our last NonConfigurationInstance

NonConfigurationInstances nc =

(NonConfigurationInstances) getLastNonConfigurationInstance();

if (nc != null) {

viewModelStore = nc.viewModelStore;

}

}

// 依然为空,说明没有需要缓存的,则返回 null

if (viewModelStore == null && custom == null) {

return null;

}

// 创建 NonConfigurationInstances 对象,并赋值 viewModelStore

NonConfigurationInstances nci = new NonConfigurationInstances();

nci.custom = custom;

nci.viewModelStore = viewModelStore;

return nci;

}

到这儿我们大概明白了,Activity 在因配置更改而销毁重建过程中会先调用 onRetainNonConfigurationInstance 保存 viewModelStore 实例。 在重建后可以通过 getLastNonConfigurationInstance 方法获取之前的 viewModelStore 实例。

现在解决了第一个问题:为什么Activity旋转屏幕后ViewModel可以恢复数据

再看第三个问题:什么时候 ViewModel#onCleared() 会被调用

public abstract class ViewModel {

protected void onCleared() {

}

@MainThread

final void clear() {

mCleared = true;

// Since clear() is final, this method is still called on mock objects

// and in those cases, mBagOfTags is null. It’ll always be empty though

// because setTagIfAbsent and getTag are not final so we can skip

// clearing it

if (mBagOfTags != null) {

synchronized (mBagOfTags) {

for (Object value : mBagOfTags.values()) {

// see comment for the similar call in setTagIfAbsent

closeWithRuntimeException(value);

}

}

}

onCleared();

}

}

onCleared() 方法被 clear() 调用了。 刚才看 ViewModelStore 源码时好像是调用了 clear() ,回顾一下:

public class ViewModelStore {

private final HashMap<String, ViewModel> mMap = new HashMap<>();

final void put(String key, ViewModel viewModel) {

ViewModel oldViewModel = mMap.put(key, viewModel);

if (oldViewModel != null) {

oldViewModel.onCleared();

}

}

final ViewModel get(String key) {

return mMap.get(key);

}

Set keys() {

return new HashSet<>(mMap.keySet());

}

/**

  • Clears internal storage and notifies ViewModels that they are no longer used.

*/

public final void clear() {

for (ViewModel vm : mMap.values()) {

vm.clear();

}

mMap.clear();

}

}

ViewModelStoreclear() 中,遍历 mMap 并调用 ViewModel 对象的 clear() , 再看 ViewModelStoreclear() 什么时候被调用的:

// ComponentActivity 的构造方法

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

}

}

}

});

}

观察当前 activity 生命周期,当 Lifecycle.Event == Lifecycle.Event.ON_DESTROY,并且 isChangingConfigurations() 返回 false 时才会调用 ViewModelStore#clear

// Activity#isChangingConfigurations()

/**

  • Check to see whether this activity is in the process of being destroyed in order to be

  • recreated with a new configuration. This is often used in

  • {@link #onStop} to determine whether the state needs to be cleaned up or will be passed

  • on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.

  • @return If the activity is being torn down in order to be recreated with a new configuration,

  • returns true; else returns false.

*/

public boolean isChangingConfigurations() {

return mChangingConfigurations;

}

isChangingConfigurations 用来检测当前的 Activity 是否因为 Configuration 的改变被销毁了, 配置改变返回 true,非配置改变返回 false

题外话

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在IT学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多程序员朋友无法获得正确的资料得到学习提升,故此将并将重要的Android进阶资料包括自定义view、性能优化、MVC与MVP与MVVM三大框架的区别、NDK技术、阿里面试题精编汇总、常见源码分析等学习资料。

【Android思维脑图(技能树)】

知识不体系?这里还有整理出来的Android进阶学习的思维脑图,给大家参考一个方向。

希望我能够用我的力量帮助更多迷茫、困惑的朋友们,帮助大家在IT道路上学习和发展~

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注Android)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在IT学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多程序员朋友无法获得正确的资料得到学习提升,故此将并将重要的Android进阶资料包括自定义view、性能优化、MVC与MVP与MVVM三大框架的区别、NDK技术、阿里面试题精编汇总、常见源码分析等学习资料。

【Android思维脑图(技能树)】

知识不体系?这里还有整理出来的Android进阶学习的思维脑图,给大家参考一个方向。

[外链图片转存中…(img-Mi2o9t7x-1713029405541)]

希望我能够用我的力量帮助更多迷茫、困惑的朋友们,帮助大家在IT道路上学习和发展~

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注Android)
[外链图片转存中…(img-vHM5KjpP-1713029405542)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值