Search code examples
androidkotlinmvvmandroid-roomkoin

How to inject Room in viewmodel using koin


This is my first mvvm project with koin and I'm using Room database. I'm making network calls in viemwodel, and after fetching data from the api I want to store it in the database. Below is my class which has all the db methods like insert and delete.

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

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 SubscriptionViewModel(): BaseViewModel() {

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

Solution

  • In general, it's a better pattern to not accessing a db object in ViewModel. 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.

    After that, you must not access a ViewModel inside another one. They should be independent. If you want to do something with the db or api in multiple ViewModels, access to them through a common repository class.

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