简体   繁体   English

如何使用Koin在另一个ViewModel中获取ViewModel实例

[英]how to get a ViewModel instance inside another ViewModel withKoin

I am new to koin and kotlin and I have just started using koin in my project and It is working quite good.我是 koin 和 kotlin 的新手,我刚刚开始在我的项目中使用 koin,它工作得很好。 I have two viewmodel classes, SubscritpionViewModel and LoginViewModel.我有两个视图模型类,SubscritpionViewModel 和 LoginViewModel。 Is there a way I can get instance of LoginViewModel inside SubscriptionViewModel.有没有办法可以在 SubscriptionViewModel 中获取 LoginViewModel 的实例。 I don't know if it is right or not but it will be handy for me if I can access the other viewmodel.我不知道它是否正确,但如果我可以访问另一个视图模型,它对我来说会很方便。

val viewModule = module {
   viewModel { SubscriptionViewModel(get(), get()) }
   viewModel { LoginViewModel(get()) }
} 

SubscriptionViewModel订阅视图模型

class SubscriptionViewModel(val api: ServiceApi,  var user: LoginViewModel) : BaseViewModel() {
   ...
} 

I have also created a separate module for this, but I don't know what is the right way to initialize it.我还为此创建了一个单独的模块,但我不知道初始化它的正确方法是什么。

val userModule = module {

single( definition = {
    get<LoginViewModel>() }) 
}

I think it's a bad design.我认为这是一个糟糕的设计。 I think what you should do is to create a common object between LoginViewModel and SubscriptionViewModel and inject it via constructor to both LoginViewModel and SubscriptionViewModel.我认为您应该做的是在 LoginViewModel 和 SubscriptionViewModel 之间创建一个公共对象,并通过构造函数将其注入到 LoginViewModel 和 SubscriptionViewModel。 Maybe Repository pattern would be good?也许存储库模式会很好? Please describe the functionality you want to implement so we can get the idea of why you need one ViewModel inside another.请描述您想要实现的功能,以便我们了解为什么您需要在另一个 ViewModel 中使用一个 ViewModel。 With repository you can do something like this:使用存储库,您可以执行以下操作:

class UserRepository(private val serviceApi: ServiceApi) {

}

class SubscriptionViewModel(val userRepository: UserRepository) : BaseViewModel() {
   ...
} 

class LoginViewModel(val userRepository: UserRepository) : BaseViewModel() {
 ...
}

and in Koin module:在 Koin 模块中:

module {
   single { UserRepository(get()) }

   viewModel { SubscriptionViewModel(get()) }
   viewModel { LoginViewModel(get()) }
} 

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

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