Home > Mobile >  How to pass context in Repository in MVVM without DI and following the clean architecture?
How to pass context in Repository in MVVM without DI and following the clean architecture?

Time:01-13

I need to initiate Room in its repository. But to do that I need context. If I pass context through the viewmodel i got this message This field leaks a context object.

I have checked this answer but they init the repository object in the view layer but according to the clean architecture view layer shouldnt know anything about data layer right? So how to organize the delivery of the context to the data layer without DI?

class MainViewModel(private val context: Context) : ViewModel() {

private val roomManager : RoomManager = RoomManagerImpl(context)

private fun addItem(){
    roomManager.addItem()
}

}

Here is repository code

class RoomManagerImpl(private val context: Context) : RoomManager {
private val db = Room.databaseBuilder(
    context,
    AppDatabase::class.java, "database-name"
)

CodePudding user response:

Passing Activity Context to the Activity's ViewModel is not a good practice it will cause memory leak.

You can get the context in your ViewModel by extending the AndroidViewModel class check below code.

It will give you application level context.

 class MainViewModel(application: Application) : AndroidViewModel(application) {

    private val context = getApplication<Application>().applicationContext
    private val roomManager: RoomManager = RoomManagerImpl(context)

    fun addItem() {
        roomManager.addItem()
    }
}

CodePudding user response:

      class MainViewModal(val repository:roomManager) :ViewModel() {
            
            fun testFunction(context: Context){
            roomManager.testMethod(context)   //text method is your repository method
        }
    }

i am telling like this I hope it's help you otherwise you can use AndroidViewModel instead of Viewmodal

  • Related