如果HolderFragment尚未create,Activity就已经销毁,则从HashMap中移除该Activity,防止泄露; HolderFragment成功创建后,从HashMap中移除该Activity; 使用HolderFragment持有的ViewModelStore对象完成ViewModelProvider的创建; 第一部分的职责是构建 / 查找HolderFragment,对构建过程中的异常做保护,最后返回ViewModelProvider。HolderFra...
可以考虑以下几种方式: 使用LiveData:利用 LiveData 观察数据变化,减少直接对 Activity 的引用。 Scoped ViewModel:在 Fragment 中使用 ViewModel,确保 ViewModel 的生命周期仅限于 Fragment 的生命周期。 WeakReference:在特殊情况下使用WeakReference来引用 Activity 或 Fragment,确保在它们不再需要时被回收。 正确的 ViewMo...
一路调用,最终走到HolderFragmentManager.holderFragmentFor(Activity); HolderFragmentManager依次从FragmentManager和HolderFragmentManager持有的HashMap查找:该Activity是否有HolderFragment与之映射(HolderFragment的作用下面一个问题将谈到); HolderFragment.classHolderFragmentholderFragmentFor(FragmentActivity activity) { Fragme...
// Get a reference to the ViewModel scoped to this Fragment val viewModel by viewModels<MyViewModel>() // Get a reference to the ViewModel scoped to its Activity val viewModel by activityViewModels<MyViewModel>() 所以我在我的 gradle(app) 中添加了以下依赖项: //ktx android implementation '...
// Get a reference to the ViewModel scoped to this Fragmentval viewModelbyviewModels<MyViewModel>()// Get a reference to the ViewModel scoped to its Activityval viewModelbyactivityViewModels<MyViewModel>() 所以我在我的 gradle(app) 中添加了以下依赖项: ...
ViewModelComponent遵循 ViewModel 的生命周期,并可以将类型的作用域限定到此组件上。由于 ViewModel 的生命周期可以被 Activity、Fragment 甚至是导航图所控制,您可以根据需要将作用域限定到这些地方,来获得更大的灵活性和更精细的控制粒度。 请使用@ViewModelScoped将类型的作用域限定为 ViewModel。使用@ActivityRetainedScop...
在依葫芦画瓢之前,必须得搞清楚activityViewModels是怎么实现的,跟踪进源码,发现activityViewModels是一个扩展函数,定义在FragmentViewModelLazy.kt文件中: AI检测代码解析 /** * Returns a property delegate to access [ViewModel] by **default** scoped to this [Fragment]: * ``` * class MyFragment : Frag...
ViewModel中使用@ActivityRetainedScoped注解,则在Fragment或者Activity中直接用Inject来实例化ViewModel 使用Flow替代LiveData可以参考module-wechat模块 对于项目中是否有必要将LiveData替换为Flow,可以参考这篇文章和这个视频 Log工具类 基于timber封装了一个工具类Logs,方便用户开发阶段和release阶段收集日志。
问通过navGraphViewModels访问子NavHostFragment的图形范围的ViewModelENViewModel 甫一发布,便成为了 Jetpack...
This diagram shows the lifecycle of three Composables (A, B, and C) with their respective objects scoped with therememberScopedfunction. All these Composables are part of a Composable destination which is part of a Fragment which is part of an Activity which is part of the App. The horizonta...