Home > OS >  Android : Using Koin How we can inject Activity context into a Class
Android : Using Koin How we can inject Activity context into a Class

Time:01-05

class ABC(context: Context){} 

class MainActivity : AppCompatActivity(){
     val abc : ABC by inject {parametersOf(this)}
     val mainViewModel : MainViewModel by viewModel {parametersOf(abc)} 
}

class MainViewModel(abc: ABC): ViewModel(){}

val appModule = module{
  factory<ABC>{params -> ABC(params.get())}
  viewModel {params -> MainViewModel(params.get())}
}

Not able to inject the activity context to the ViewModel

CodePudding user response:

Similar question has been asked here. Please follow to get the updated answer:- How to inject activity context in modules with koin dependency library

CodePudding user response:

Instead of ViewModel() you can extend the AndroidViewModel() like this:

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

And call it by

getApplication<Application>().applicationContext

But as far as i know its not recommended to do.

  •  Tags:  
  • Related