如何为许多片段创建ViewModel实例?

发布于 2025-02-07 00:30:38 字数 946 浏览 0 评论 0原文

我的活动中有很多片段,每种片段都使用VM中的方法。在每个片段中,我都必须在以这种方式使用它之前创建ViewModel实例:

val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
    this@FragmentName,
    AppVMFactory(mainRepository)
).get(AppViewModel::class.java)

在我的Mainrepository中,我有我的请求方法:

class MainRepository constructor(private val retrofitService: RetrofitService) {
    suspend fun someMethod() = retrofitService.someMethod()
}

在改造服务中,我有API请求方法。主要问题是我如何仅一次不使用此代码来创建ViewModel实例:

val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
    this@FragmentName,
    AppVMFactory(mainRepository)
).get(AppViewModel::class.java)

在每个片段中。一开始,我考虑了单个片段父母,但是我不确定对话范围是否可以以及如何与数据绑定一起使用。也许我可以使用我不知道的Android开发的某些功能?

I have a lot of fragments in my activity, each of which uses own methods in the VM. In each of fragment I have to create viewmodel instance before using it in such way:

val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
    this@FragmentName,
    AppVMFactory(mainRepository)
).get(AppViewModel::class.java)

in my MainRepository I have my requests methods:

class MainRepository constructor(private val retrofitService: RetrofitService) {
    suspend fun someMethod() = retrofitService.someMethod()
}

and in retrofit service I have api requests methods. The main question is how I cane create viewModel instance only one time without using this code:

val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
    this@FragmentName,
    AppVMFactory(mainRepository)
).get(AppViewModel::class.java)

in each fragment. At the beginning I thought about single fragment parent, but I'm not sure whether it will be ok for dialogFragment and also how it will be able to use with data binding. Maybe I can use some features of android development about which I don't know?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱不及久伴 2025-02-14 00:30:38

您可以使用sharedViewModel,并且将在活动中的所有片段中共享 https:/// developer.android.com/topic/libraries/architecture/viewmodel#sharing

You can use sharedViewModel and it will be shared across all fragments in activity https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文