简体   繁体   English

如何使用 koin 在视图模型中注入 Room

[英]How to inject Room in viewmodel using koin

This is my first mvvm project with koin and I'm using Room database.这是我第一个使用 koin 的 mvvm 项目,我正在使用 Room 数据库。 I'm making network calls in viemwodel, and after fetching data from the api I want to store it in the database.我在 viemwodel 中进行网络调用,从 api 获取数据后,我想将其存储在数据库中。 Below is my class which has all the db methods like insert and delete.下面是我的 class ,它具有插入和删除等所有数据库方法。

class UserViewModel(application: Application) : AndroidViewModel(application) {
   
    private val userSDAO: UserDAO
    private val userDB: AppSettingsDatabase

    init {
        userDB = AppSettingsDatabase.getAppSettingsDatabase(application.applicationContext)!!
        userDAO = userDB.userDao()
    }

    fun getAppSetting():LiveData<AppSettingsEntity>{
        return userDB.appSettingDao().getAllAppSettings()
    }

    fun deleteUser() {
        userDB.databaseWriteExecutor.execute { ->
            userDAO.deleteUser()
        }
    }
}

I was calling this class from activity like this我从这样的活动中调用这个 class

userViewModel = ViewModelProvider(this).get(UserViewModel::class.java)

now I want to call this inside a viewmodel class where I am making the network api calls and I don't know what is the best approach to access it using koin, or any other way.I have different methods where I need database access and I have to initialize it like above in every method.现在我想在视图模型 class 中调用它,我在其中进行网络 api 调用,但我不知道使用 koin 或任何其他方式访问它的最佳方法是什么。我有不同的方法需要数据库访问和我必须在每种方法中都像上面一样初始化它。

class SubscriptionViewModel(): BaseViewModel() {

    fun init(owner:ViewModelStoreOwner) { 
        userServiceViewModel = ViewModelProvider(owner).get(UserServiceViewModel::class.java)
    } 
}

In general, it's a better pattern to not accessing a db object in ViewModel .一般来说,在ViewModel中不访问数据库 object 是一种更好的模式。 I mean the dao should be used in a data source class, then the data source would be injected in the ViewModel or even better, use the data source in a repository, then inject the repository in the ViewModel .我的意思是应该在数据源 class 中使用 dao,然后将数据源注入ViewModel甚至更好,在存储库中使用数据源,然后在ViewModel中注入存储库。

After that, you must not access a ViewModel inside another one.之后,您不能访问另一个ViewModel中的 ViewModel。 They should be independent.他们应该是独立的。 If you want to do something with the db or api in multiple ViewModel s, access to them through a common repository class.如果您想在多个ViewModel中使用 db 或 api 做某事,请通过公共存储库 class 访问它们。

Please take a look at: https://developer.android.com/jetpack/guide#overview请看一下: https://developer.android.com/jetpack/guide#overview

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

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